Python的scopy框架的简单使用
首先通过终端安装scrapy爬虫框架:pip install scrapy
scrapy是一个多线程的爬虫框架,它的运行原理如下:
加粗样式
1,引入request模块,用来完成网络请求(如果没有requests模块,使用pip安装)
import requests,os
#完成网络数据请求
header={
‘user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ’
‘(KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36’
}
#构建get请求
if not os.path.exists(’./txt.html’):
reponse=requests.get(‘http://www.su74.com/’,headers=header)
with open(’./txt.html’,‘w’,encoding=‘UTF-8’) as f:
f.write(reponse.text)
“”"
requests返回的responses对象的属性
text–将网页源代码转化成字符串类型
content–将网页源代码转换成二进制数据类型
status_code–返回当前服务器响应的状态码
cookies–返回当前网页请求对应的cookie信息
encoding–返回当前网页的编码格式
“”"
#网页解析
with open(’./txt.html’,‘r’,encoding=‘UTF-8’) as f:
text=f.read()
#将字符串数据转换成HTML树形解构
from lxml import etree
html=etree.HTML(text)
#xpath解析–基于xml的路径解析,该解析速度和BeautifulSoup解析速度相同,但是内存开销比较小
同时xpath解析速度远高于普通的xml解析
“”"
xpath的各种解析指令
/div–代表查找根节点为div的标签
/div/p–代表查找div标签内部直接子集元素为p标签
//div–代表查找任意位置的div标签
div//p–代表查找div下的任意位置的p标签
//div[@class]–查找任意位置带有class属性的div标签
//div[@class=‘aaa’]–查找任意位置带有class属性的div标签
//div/text()–查找任意位置的div标签内部的文本内容
//a/@href–获取任意位置的a标签的href属性
//a[1]–代表获取任意位置a标签中的第一个标签
//div[@class=‘aaa’ and @id=‘bbb’]–获取class属性为aaa且id为bbb的任意位置的div标签
//div[@class=‘aaa’ or @class=‘bbb’]获取class属性为aaa或bbb的任意位置的div标签
//div[contains(@class,‘aaa’)]–获取指定属性class中包含‘aaa’内容的标签
//div[starts-with(@class,‘aaa’)]–获取class属性以aaa开头的任意位置的div标签
“”"
datas=html.xpath(’//’)
2,模拟浏览器操作
from selenium import webderiver
from selenium.webdirever.support.wait import WebDriverWait
import time
#引入webdriver模拟浏览器操作,引入time模块设置爬取间隔
#创建浏览器
browser=webderiver.Chrome()
#创建wait对象,用来设置等待浏览器加载页面的最长等待时间
try:
#浏览器加载
browser.get(‘https://www.jd.com’)
js="""
function scroll(height){
window.scrollTo(0,height);
}
scroll(arguments[0]);
“”"
height=0
for i in range(100):
height+=500
browser.execute_script(js,height)
time.sleep(0.5)
finally:
time.sleep(60)
#退出浏览器
browser.quit()