Python Webscrape带参数的谷歌自定义搜索URL



我正在尝试做一个项目,在这个项目中,我使用谷歌图像和谷歌的自定义搜索API来搜索类似的图像。从中,我得到了正确的URL,可以得到类似的图像。然后,我只需要该页面的HTML。页面看起来像这个链接。我只想要HTML到这导致的页面。但是,我尝试了这个:

r = requests.get(fetchUrl)
print(r.text)

这只是一个真正古老的谷歌主页的HTML。我不确定这是从哪里来的。我还试着添加了一个标题,以确保谷歌不会阻止我抓取。

完整代码:

import requests
filePath = 'Initial_Img/a/frame1.jpg'
searchUrl = 'http://www.google.com/searchbyimage/upload'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
response = requests.post(searchUrl, files=multipart, allow_redirects=False)
fetchUrl = response.headers['Location']
print(fetchUrl)

你有什么想法吗?任何帮助都将不胜感激。

问题出在Google呈现页面的方式上。您必须使用Selenium并实际使用web浏览器才能获得HTML。解决您的问题:

运行:sudo apt install firefox-geckodriver并安装Firefox

运行:pip install selenium

将您的代码更改为:

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
filePath = 'Initial_Img/a/test.jpg'
searchUrl = 'http://www.google.com/searchbyimage/upload'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''}
response = requests.post(searchUrl, files=multipart, allow_redirects=False)
fetchUrl = response.headers['Location']
options = Options()
options.add_argument("--disable-extensions")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox") # linux only
options.add_argument("--headless")
options.headless = True # also works
nav = webdriver.Firefox(options=options)
nav.get(fetchUrl)
print(nav.page_source)

nav.page_source将为您提供结束页的HTML。我希望这能有所帮助。我不知道为什么正常的方法不起作用。如果有人知道原因,请在下面评论。

最新更新