【发布时间】:2016-02-16 17:25:29
【问题描述】:
我想使用 Google 图片搜索下载批量图片。
我的第一个方法;将页面源下载到文件中,然后使用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 文件时,脚本按预期工作,并且我得到了搜索页面上所有图像 url 的简洁列表。这就是脚本第 6 行的作用(取消注释以进行测试)。
但是,如果我使用requests.get() 函数来解析网页,如脚本的第 7 行所示,它会获取一个 不同的 html 文档,该文档不包含图片,所以我无法提取它们。
请帮我提取图片的正确网址。
编辑: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])
【问题讨论】:
标签: python html web-scraping google-image-search