其实,selenium 或 regex 是不需要的。
您正在寻找此链接以获取第一个链接(查看SelectorGadget Chrome 扩展程序以通过单击浏览器中的元素来获取 CSS 选择器): p>
first_link = soup.select_one('.yuRUbf a')['href']
# https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors
另外,下一个问题可能是因为没有指定user-agent,Google 最终会阻止请求,您将收到完全不同的 HTML。
代码和example in the online IDE:
from bs4 import BeautifulSoup
import requests, lxml
headers = {
'User-agent':
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
params = {
"q": "ABCD filetype:pdf", # query
"gl": "us", # country to search from
"hl": "en" # language
}
html = requests.get("https://www.google.com/search", headers=headers, params=params)
soup = BeautifulSoup(html.text, 'lxml')
first_link = soup.select_one('.yuRUbf a')['href']
print(first_link)
# https://resources.depaul.edu/abcd-institute/resources/Documents/WhatisAssetBasedCommunityDevelopment.pdf
或者,您可以使用来自 SerpApi 的 Google Organic Results API 来实现相同的目的。这是一个带有免费计划的付费 API。
您的情况的不同之处在于,您只需要迭代结构化 JSON 并快速获取所需的数据,而不是弄清楚为什么某些事情不能按预期工作并且您不必维护解析器时间。
要集成的代码:
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "bABCD filetype:pdf",
"hl": "en",
"gl": "us",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
first_link = results['organic_results'][0]['link']
print(first_link)
# https://dohcoey14i4kf.cloudfront.net/sites/default/files/despiece_maquina_mc507_0.pdf
免责声明,我为 SerpApi 工作。