我想用Google图片搜索下载批量图片。用Python3刮去Google图片(请求+ BeautifulSoup)
我的第一种方法;将页面源文件下载到一个文件,然后用open()
打开它可以正常工作,但我希望能够通过运行脚本和更改关键字来获取图像URL。
第一种方法:转到图像搜索(https://www.google.no/search?q=tower&client=opera&hs=UNl&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiM5fnf4_zKAhWIJJoKHYUdBg4Q_AUIBygB&biw=1920&bih=982)。在浏览器中查看页面源并将其保存为html文件。当我然后open()
与脚本的HTML文件,该脚本按预期工作,我得到了搜索页上图像的所有网址的整齐列表。这是脚本的第6行(取消注释以测试)。
但是如果我使用requests.get()
函数来解析网页,如图脚本的7号线,它取一个不同 html文件,不包含图像的完整URL,所以我不能提取他们。
请帮我提取正确的图像网址。
编辑:链接到tower.html,我使用:https://www.dropbox.com/s/yy39w1oc8sjkp3u/tower.html?dl=0
这是代码,我至今写:
import requests
from bs4 import BeautifulSoup
# define the url to be scraped
url = 'https://www.google.no/search?q=tower&client=opera&hs=cTQ&source=lnms&tbm=isch&sa=X&ved=0ahUKEwig3LOx4PzKAhWGFywKHZyZAAgQ_AUIBygB&biw=1920&bih=982'
# top line is using the attached "tower.html" as source, bottom line is using the url. The html file contains the source of the above url.
#page = open('tower.html', 'r').read()
page = requests.get(url).text
# parse the text as html
soup = BeautifulSoup(page, 'html.parser')
# iterate on all "a" elements.
for raw_link in soup.find_all('a'):
link = raw_link.get('href')
# if the link is a string and contain "imgurl" (there are other links on the page, that are not interesting...
if type(link) == str and 'imgurl' in link:
# print the part of the link that is between "=" and "&" (which is the actual url of the image,
print(link.split('=')[1].split('&')[0])
我曾尝试使用urllib的,这主要是给了我“禁止”回刮,这是我相信是因为禁止,你提到。 urllib适用于除谷歌图像以外的任何内容。 我知道在请求解析的文本中没有“imgurl”-s。 你得到的结果是图像的缩略图。这比没有好,但我想收获全分辨率的图像。 问题是解析从不包含那个。有没有什么办法可以让请求遵循脚本,并且实际上让它获取源图像的地址? –
这就是为什么它给你“禁止”回来。他们已经构建了一个完整的模块来解析网站的robots.txt文件,并确定是否允许抓取。您可以尝试使用're'库并使用正则表达式来查找值。但是,我认为Google的搜索页面很难找到......他们很难找到原因。 – ngoue
无论如何,感谢编辑提取缩略图:) –