我一直试图使用下面的代码获得第一个搜索结果。代码适用于某些情况,但在某些情况下,它提供的输出是不完整的。
码:
import requests
from bs4 import BeautifulSoup
research_later = "ABCD filetype:pdf"
goog_search = "http://google.com/search?q=" + research_later
r = requests.get(goog_search)
soup = BeautifulSoup(r.text, "html.parser")
print(soup.find('cite').text)
输出:
www.altogetherbetter.org.uk/.../5-assetbasedcommunitydevelopment.pdf
实际输出应为:
http://www.altogetherbetter.org.uk/Data/Sites/1/5-assetbasedcommunitydevelopment.pdf
以下是我用来解决问题的代码。在找到网络链接后,我下载了文件,这是我的最终目标。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(executable_path=r'C:\chromedriver_win32\chromedriver.exe', chrome_options=options)
research_later = "ABCD filetype:pdf"
driver.get("http://google.com/search?q="+research_later)
elem=driver.find_element_by_css_selector("#rso > div > div > div:nth-child(1) > div > div > h3 > a").click()
似乎引用标记不包含整个链接。您可能希望从“a”标记中获取它。试试这个:
import re
regex = re.compile(r'https://(.)+')
elem = soup.find('a',attrs={'href':re.compile(r'/url?')})['href']
regex.search(elem).group()
这将为您提供链接,但您可能需要使用另一个正则表达式进行格式化。