python使用chrome driver做简单爬虫--转载于简书

使用pythonurllib来抓取网页很容易被当作爬虫来对待

下面是一个使用urllib的例子:
import urllib.request
url = 'http://www.jianshu.com/p/99747a2f29f7'
headers = {
    'Connection': 'Keep-Alive',
    'Accept': 'text/html, application/xhtml+xml, */*',
    'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
req = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(req)
html = response.read().decode()
print(html)
使用selenium

为了防止这种情况,我们可以使用selenium自动控制chrome等浏览器抓取网页数据,使用以上方式抓取网页内容的,还可以让浏览器动态的加载网页内容,这方便了抓取使用ajax动态加载的网页

代码要点:
  1. 使用webdriver调用chrome driverC:\Program Files (x86)\Google\Chrome\Application\chromedriver.exechrome driver的安装路径
browser = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
获取到网页的html代码之后,可以使用BeautifulSoup查找网页标签,通过BeautifulSoup初始化一个bsObj对象之后,可以使用findfind_all查找网页标签,查找到的标签还是继续使用findfind_all方法
bsObj = BeautifulSoup(html, "html.parser")
note_list = bsObj.find("ul", {"class": "note-list"})
article_list = note_list.find_all("li")
  1. 如何获得某个标签中的属性,如获得<a />中的href属性 
href = i.find('a', {"class": "title"})['href']

 

  1. 如何获得标签中夹杂的文本,如<p> 文本内容 </p>,可以使用get_text方法
times = i.find('div', {"class": "meta"}).a.get_text()

完整代码:

from selenium import webdriver
from bs4 import BeautifulSoup
import time


def get_all_article(uid):
    tar_url = 'http://www.jianshu.com/u/' + uid
    browser.get(tar_url)
    html = browser.page_source
    bsObj = BeautifulSoup(html, "html.parser")
    note_list = bsObj.find("ul", {"class": "note-list"})
    article_list = note_list.find_all("li")
    all_article = []
    for i in article_list:
        href = i.find('a', {"class": "title"})['href']
        times = i.find('div', {"class": "meta"}).a.get_text().strip('\n').strip()
        all_article.append({'href': href, 'times': times})
    return all_article

browser = webdriver.Chrome('C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe')
browser.set_page_load_timeout(5)
uid = '55672ec82fcd'
all_article = get_all_article(uid=uid)
for article in all_article:
    times = int(article['times'])
    if times < 10:
        for j in range(10-times):
            try:
                browser.get('http://www.jianshu.com'+article['href'])
                time.sleep(0.2)
            except Exception as e:
                continue
browser.quit()

注意:

chrome driver下载时一定要版本对应,

这里是chrome driver的下载地址,如果速度太慢,建议使用vpn打开

chrome driverchrome之间的对应关系,可以查看各个版本下面的notes.txt文件

作者:JzCh
链接:https://www.jianshu.com/p/4b84a7d7e567
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
posted @ 2020-07-09 22:48    阅读(980)  评论(0编辑  收藏  举报