from selenium import webdriver
import re
driver= webdriver.Chrome(executable_path=r"C:\Users\chromedriver")
sentence = "chiropractor in maryland"
url="https://google.com/search?hl=en&q={}".format(sentence)
driver.get(url)
links=driver.find_elements_by_xpath('//a[@href]')
maps=[i for i in links if i.text=="Maps"][0].click()
html=driver.page_source
#ChIJaYGxdRj9t4kRcJmJlvQkKX0
#ChIJCf4MzWjgt4kRluBnhQTHlBM
#ChIJBXxr8brIt4kRVE-gIYDyV8c
#ChIJX0W_Xo4syIkRUAtRFy8nz1Y place ids in html


您好,这是我的第一个硒项目,我试图从结果中找到地方ID,我已经添加了一些地方ID(我使用API​​),我试图在检查器工具中找到它们,但我无法,但是在我尝试使用正则表达式的页面源中可用,看来它们遵循以下路径

2,[null,null,\\"bizbuilder:gmb_web\\",[6,7,4,1,3]\\n]\\n]\\n]\\n,1,null,null,null,null,null,null,[\\"-8523065488279764631\\",\\"9018780361702349168\\"]\\n]\\n]\\n]\\n,null,null,null,[[\\"chiropractor\\"]\\n]\\n,null,\\"ChIJaYGxdRj9t4kRcJmJlvQkKX0\\",null,null,null,[\\"South Gate\\",\\"806 Landmark Dr Suite 126\\",\\"806 Landmark Dr Suite 126\\",\\"Glen Burnie\\"]\\n,null,null,null,null,null,[null,\\"SearchResult.TYPE_PERSONAL_


“ \”脊医之后] \ n] \ n,null,\“ Place ID”,null ...

但我找不到它的正则表达式。
我需要帮助来编写正确的正则表达式或寻找另一种找到palce_id的方法。
我希望没人回答使用他们的API

最佳答案

我认为可以对此进行改进,但字符串本身位于包含window.APP_OPTIONS的脚本标签中。这些ID中的每个ID均以ChIJ开头,后跟已定义的字符集,并且总长度为27。

我也直接从地图页面开始,而不是单击它。尽管运行了几次,但我不需要等待条件。如果需要/需要,可以添加。

from selenium import webdriver
from bs4 import BeautifulSoup as bs
import re

sentence = "chiropractor in maryland"
url = 'https://www.google.com/maps/search/{}'.format(sentence)
d = webdriver.Chrome()
d.get(url)
soup = bs(d.page_source, 'lxml')

for script in soup.select('script'):
    if 'window.APP_OPTIONS' in script.text:
        script = script.text
        break
r = re.compile(r'(ChIJ[a-zA-Z\.0-9\-\_]{23})')
items = r.findall(script)
print(items)

d.quit()




稍微冒险一点,您可以直接使用page_source

from selenium import webdriver
from bs4 import BeautifulSoup as bs
import re

sentence = "chiropractor in maryland"
url = 'https://www.google.com/maps/search/{}'.format(sentence)
d = webdriver.Chrome()
d.get(url)
r = re.compile(r'(ChIJ[a-zA-Z\.0-9\-\_]{23})')
items = r.findall(d.page_source)
print(items)

d.quit()




笔记:

我指定了一种模式,该模式旨在仅与当前所需项匹配(对于给定搜索)。可以想象,在将来的/新的搜索中,该模式可能会发生,而不是一个id。 page_source是一个较大的搜索空间,因此遇到匹配该模式的不需要的字符串的可能性更大。脚本标签不仅在您希望找到ID的位置,而且是一个较小的搜索空间。随着时间的流逝,您可能还希望检查字符集是否不需要任何其他字符来匹配新的ID。您可以轻松地对照每页计数结果。

关于python - 谷歌 map 使用 Selenium 的地方ID,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55771291/

10-12 14:01
查看更多