抓取百度上的图片链接

采用urllib

最开始打算用入门级别的 urllib,不过出现了很多问题

keyword = '回族明星'
# 使用baidu的搜索功能,经过测试发现不能用https,非常头疼
baiduUrl = 'http://www.baidu.com/s?wd='

import urllib.request
keywordCoding = urllib.request.quote(keyword)
req = urllib.request.Request(baiduUrl+keywordCoding, method = 'GET')
data = urllib.request.urlopen(req,timeout=50)
d = data.read()
# 得到html,decode用于解码,使用'utf-8'
html = d.decode('UTF-8')

虽然抓取到了 html 不过和正常https得到的图片url不一致,只能在同一个浏览器使用对应的url,否则无法下载图片。因此还是需要采用https的方法发出请求。

使用selenium

selenium使用时需要浏览器和浏览器驱动支持,此处选择了chrome浏览器,配以chromedriver,这个驱动只能翻墙下载,大家就自求多福吧。

安装完成后,还需要

pip install beautifulsoup4

用于进行html的解析。

具体的代码见下面

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from selenium import webdriver
import urllib.request
from bs4 import BeautifulSoup 
import requests
import sys,os
#这部分判断命令行参数,不重要
if len(sys.argv)>1:
    keyword = sys.argv[1]
else:
    keyword = input('输入某个民族比如"回族明星":')
# 这部分创建文件夹,不重要
if os.path.exists(keyword):
    print("将重写{}文件夹".format(keyword))
else:
    print('创建{}文件夹'.format(keyword))
    os.mkdir(keyword)
# 这部分采用selenium进行抓取,用beautifulsoup进行html解析
keywordCoding = urllib.request.quote(keyword)
baiduUrl = 'https://www.baidu.com/s?wd='
browser = webdriver.Chrome()
print('向百度发起请求')
browser.get(baiduUrl + keywordCoding)
print('抓取完毕')
html = browser.page_source

soup =  BeautifulSoup(html, 'html.parser')
img = soup.find_all(attrs='op_exactqa_item_img')
for im in img:
    print('从{}获取{}明星图片'.format(im.img['src'],im.a['title']))
    r = requests.get(im.img['src'])
    with open(keyword+'/'+im.a['title']+'.png','wb') as opt:
        opt.write(r.content)

browser.quit()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章