这一系列日志将记录我从0开始学习爬虫的过程,并计划在一个月以内掌握爬虫。html
爬虫用到的库,BeautifulSoup4,requests,lxmlpython
首先导入库浏览器
from bs4 import BeautifulSoup import requests
将要爬取的网页的网址保存在字符串变量url中cookie
url='xxx.html'
使用requests中的get函数爬取网页内容,并保存在变量wb_data中。函数
wb_data=requests.get(url)
get函数能够带参数,建立一个字典保存User-Agent和Cookie等信息,将字典赋给get函数中的参数headers能够用伪造的用户信息爬取用户登录以后的网页。学习
#headers={'User-Agent':xxx,'Cookie':xxx} #wb_data=requests.get(url,headers=headers) #wb_data所保存的信息 ''' wb_data.text-网页的代码 wb_data.status_code-状态码 wb_data.url-请求url wb_data.headers-头信息 wb_data.cookies-cookie信息 wb_data.content-字节流的形式 '''
将数据用BeautifulSoup进行解析,保存在soup变量中。url
soup=BeautifulSoup(wb_data.text,'lxml')#用lxml方式解析
以后用select函数从soup中选取要爬取的数据便可,如爬取标题:日志
titles=soup.select('a.location-name')#引号里的是路径,在chorme浏览器下,检查元素,右键copy selector所复制的内容 #可在标签后加上筛选的条件,imgs=soup.select("img.photo_image[width='160']")
一些辅助函数get_text()可去掉标签,提取出文本,get函数可提取标签里的内容,如code
title=title.get_text() img=img.get('src')