【发布时间】:2022-11-23 15:57:48
【问题描述】:
当给定关键字列表时,我试图在谷歌上搜索相关搜索,然后将这些相关搜索输出到一个 csv 文件中。我的问题是获取漂亮的汤来识别相关搜索 html 标签。
这是源代码中的示例 html 标记:
<div data-ved="2ahUKEwitr8CPkLT3AhVRVsAKHVF-C80QmoICKAV6BAgEEBE">iphone xr</div>
这是我的网络驱动程序设置:
from selenium import webdriver
user_agent = 'Chrome/100.0.4896.60'
webdriver_options = webdriver.ChromeOptions()
webdriver_options.add_argument('user-agent={0}'.format(user_agent))
capabilities = webdriver_options.to_capabilities()
capabilities["acceptSslCerts"] = True
capabilities["acceptInsecureCerts"] = True
这是我的代码:
queries = ["iphone"]
driver = webdriver.Chrome(options=webdriver_options, desired_capabilities=capabilities, port=4444)
df2 = []
driver.get("https://google.com")
time.sleep(3)
driver.find_element(By.CSS_SELECTOR, "[aria-label='Agree to the use of cookies and other data for the purposes described']").click()
# get_current_related_searches
for query in queries:
driver.get("https://google.com/search?q=" + query)
time.sleep(3)
soup = BeautifulSoup(driver.page_source, 'html.parser')
p = soup.find_all('div data-ved')
print(p)
d = pd.DataFrame({'loop': 1, 'source': query, 'from': query, 'to': [s.text for s in p]})
terms = d["to"]
df2.append(d)
time.sleep(3)
df = pd.concat(df2).reset_index(drop=False)
df.to_csv("related_searches.csv")
它的 p=soup.find_all 是不正确的我只是不确定如何让 BS 识别这些特定的 html 标签。任何帮助都会很棒:)
【问题讨论】:
-
谷歌不允许抓取并且它的 html 代码是高度动态的(生成的类等),所以它没有帮助。我不鼓励尝试抓取 Google 并找到 API 替代品
-
好的,谢谢提醒,关于好的 api 有什么建议吗?
-
使用谷歌的 API。
标签: python selenium google-chrome web-scraping beautifulsoup