一、Xpath的使用
html = etree.HTML(doc)
a = html.xpath('//*') # 所有节点
a = html.xpath('//head') # 指定head节点
a = html.xpath('//head') # 指定节点为列表
a = html.xpath('//div/a') # 子节点里面的子孙节点 div>a
a = html.xpath('//body//a') # 子节点里面的子孙节点 div>a
a = html.xpath('//body//a[@href="image1.html"]/..') # 上一节点 div a..
a = html.xpath('//body//a[1]/..') # 第一个a标签..
a = html.xpath('//body//a[1]/parent::*') # 也可以通过 parent * div
a = html.xpath('//body//a[1]/parent::div')
a = html.xpath('//body//a[@href="image1.html"]') # 属性匹配 标签为 a
a = html.xpath('//body//a[@href="image1.html"]/text()') # 内容获取 a标签内的内容['Name: My image 1 ']
a = html.xpath('//body//a/@href') # 属性获取 获取所有标签里面的a
a = html.xpath('//body//a/@id') # 属性获取
a = html.xpath('//body//a[1]/@id') # 属性获取 从1开始不是0
a = html.xpath('//body//a[@class="li"]') # 属性多值匹配 a 标签有多个class类,直接匹配就不可以了,需要用contains
a = html.xpath('//body//a[@name="items"]') # 属性多值匹配 匹配a标签内有name = items的标签
a = html.xpath('//body//a[contains(@class,"li")]') # 属性多值匹配 匹配a标签内有class = li的标签
a = html.xpath('//body//a[contains(@class, "li")]/text()') # 属性多值匹配 匹配a标签内有class = li的标签的值
a = html.xpath('//body//a[contains(@class, "li") or @name="itmes"]/text()') # 多属性匹配 匹配a标签内有class=li or name=itmes的内容
a = html.xpath('//body//a[contains(@class,"li") and @name="items"]/text()') # 多属性匹配 匹配a标签内有class=li and name=itmes的内容
a = html.xpath('//a[2]/text()') # 按序选择 查找第二个a标签的内容
a = html.xpath('//a[3]/@href') # 按序选择 查找第三个a标签的@href内容
a = html.xpath('//a[last()]/@href') # 按序选择 查找最后一个a标签的@href内容
a = html.xpath('//a[position()<3]/@href') # 按序选择 查找标签位置小于3的位置
a = html.xpath('//a[last()-2]/@href') # 按序选择 查找倒数第二个a标签
a = html.xpath('//a/ancestor::*') # ancestor:祖先节点 使用了* 获取所有祖先节点
a = html.xpath('//a/ancestor::div') # 获取祖先节点中的div
a = html.xpath('//a[1]/attribute::*') # 获取第一个a标签的属性值
a = html.xpath('//a[1]/attribute::href') # 获取第一个a标签的href属性值
a = html.xpath('//a[1]/child::*') # 获取第一个a标签的的子节点
a = html.xpath('//a[6]/descendant::*') # 获取第六个a标签的子节点
a = html.xpath('//a[1]/following::*') # 获取第一个a标签之后的所有节点
a = html.xpath('//a[1]/following::*[1]/@href') # 获取第1个a标签之后的所有节点里面的第一个href里面所有的节点
a = html.xpath('//a[1]/following-sibling::*') # 获取第一个a标签之后所有同级节点
a = html.xpath('//a[1]/following-sibling::a') # 获取第一个a标签之后同级a节点
a = html.xpath('//a[1]/following-sibling::*[2]') # 获取第一个a标签之后所有同级节点第二个节点
a = html.xpath('//a[1]/following-sibling::*[2]/@href') # 获取第一个a标签之后所有同级节点第二个节点里面href的属性
print(a)
二、Selenium动作链
方式1: 一下拖到顶
actions=ActionChains(bro) #拿到动作链对象
actions.drag_and_drop(sourse,target) #把动作放到动作链中,准备串行执行
actions.perform()
方式2: 慢慢拖
ActionChains(bro).click_and_hold(sourse).perform()
distance=target.location['x']-sourse.location['x']
track=0
while track < distance:
ActionChains(bro).move_by_offset(xoffset=2,yoffset=0).perform()
track+=2
三、自动登录12306
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--disable-blink-features=AutomationControlled") # 12306会监测到自动化这项配置去掉自动化控制的提示
bro = webdriver.Chrome(executable_path='./chromedriver', options=options)
bro.get('https://kyfw.12306.cn/otn/resources/login.html')
bro.maximize_window() # 打开页面打开全屏
bro.implicitly_wait(10) # 使用selenium控制浏览器 它的滑块不会显示出来 需要使用这个等待
try:
username = bro.find_element(by=By.ID, value='J-userName')
username.send_keys('账号')
password = bro.find_element(by=By.ID, value='J-password')
password.send_keys('密码')
time.sleep(3)
btn = bro.find_element(by=By.ID, value='J-login')
btn.click()
span = bro.find_element(by=By.ID, value='nc_1_n1z')
ActionChains(bro).click_and_hold(span).perform() # 鼠标左键一直按住的状态
ActionChains(bro).move_by_offset(xoffset=300, yoffset=0).perform() # x轴滑动
time.sleep(10)
except Exception as e:
print(e)
finally:
bro.close()
四、使用打码平台自动登录
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from chaojiying import ChaojiyingClient
from PIL import Image
bro = webdriver.Chrome(executable_path='./chromedriver.exe')
bro.get('https://www.chaojiying.com/apiuser/login/')
bro.implicitly_wait(10)
bro.maximize_window()
try:
username = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[1]/input')
password = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[2]/input')
code = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[3]/input')
btn = bro.find_element(by=By.XPATH, value='/html/body/div[3]/div/div[3]/div[1]/form/p[4]/input')
username.send_keys('密码')
password.send_keys('账号')
bro.save_screenshot('main.png') # 整个页面截图
img = bro.find_element(By.XPATH, '/html/body/div[3]/div/div[3]/div[1]/form/div/img') # 使用pillow,从整个页面中截取出验证码图片 code.png
location = img.location # 定位验证码xy轴
size = img.size
print(location)
print(size) # 使用pillow扣除大图中的验证码
img_tu = (int(location['x']), int(location['y']), int(location['x'] + size['width']), int(location['y'] + size['height']))
img = Image.open('./main.png') # 抠出验证码
fram = img.crop(img_tu) # 抠图
fram.save('code.png') # 截出来的小图
chaojiying = ChaojiyingClient('账号', '密码', 'xxxx软件ID') # 使用超级鹰破解 用户中心>>软件ID 生成一个替换 xxxxID
im = open('code.png', 'rb').read() # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//
print(chaojiying.PostPic(im, 1902)) # 1902 验证码类型 官方网站>>价格体系 3.4+版 print 后要加()
res_code = chaojiying.PostPic(im, 1902)['pic_str']
code.send_keys(res_code)
time.sleep(5)
btn.click()
time.sleep(10)
except Exception as e:
print(e)
finally:
bro.close()
五、使用Selenium爬去JD商品信息
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.keys import Keys
def get_goods(driver):
try:
goods = driver.find_elements(by=By.CLASS_NAME, value='gl-item')
for good in goods:
name = good.find_element(by=By.CSS_SELECTOR, value='.p-name em').text
price = good.find_element(by=By.CSS_SELECTOR, value='.p-price i').text
commit = good.find_element(by=By.CSS_SELECTOR, value='.p-commit a').text
url = good.find_element(by=By.CSS_SELECTOR, value='.p-name a').get_attribute('href')
img = good.find_element(by=By.CSS_SELECTOR, value='.p-img img').get_attribute('src')
if not img:
img ='https://'+ good.find_element(by=By.CSS_SELECTOR, value='.p-img img').get_attribute('data-lazy-img')
print('''
商品名字:%s
商品价格:%s
商品链接:%s
商品图片:%s
商品评论:%s
''' % (name, price, url, img, commit))
button = driver.find_element(by=By.PARTIAL_LINK_TEXT, value='下一页')
button.click()
time.sleep(1)
get_goods(driver)
except Exception as e:
print(e)
def spider(url, keyword):
driver = webdriver.Chrome(executable_path='./chromedriver')
driver.get(url)
driver.implicitly_wait(10) # 使用隐式等待
try:
input_tag = driver.find_element(by=By.ID, value='key')
input_tag.send_keys(keyword)
input_tag.send_keys(Keys.ENTER)
get_goods(driver)
finally:
driver.close()
if __name__ == '__main__':
spider('https://www.jd.com/', keyword='iphone14promax')
六、Scrapy介绍
前面讲的都是使用模块 做专业的爬虫可以使用框架Scrapy爬虫框架(做爬虫用的东西都封装好了只需要在固定的位置写固定的代码即可)
Scrapy一个开源和协作的框架,其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的,使用它可以以快速、简单、可扩展的方式从网站中提取所需的数据。但目前Scrapy的用途十分广泛,可用于如数据挖掘、监测和自动化测试等领域,也可以应用在获取API所返回的数据或者通用的网络爬虫
Mac、Linux安装Scrapy
pip3 install scrapy // 如果在终端内安装报错 可以在pycharm里面试试
Win安装Scrapy
1、pip3 install wheel
2.pip3 install lxml
3.pip3 install pyopenssl
4.下载并安装pywin32:https://sourceforge.net/projects/pywin32/files/pywin32/
5.下载twisted的wheel文件:http://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted
6.执行pip3 install 下载目录\Twisted-17.9.0-cp36-cp36m-win_amd64.whl
7.pip3 install scrapy
创建爬虫项目
1.创建项目
scrapy startproject 爬虫名称
2.创建爬虫
scrapy genspider cnblogs www.cnblogs.com
3.scrapy crawl cnblogs --nolog # --log 取消日志功能
4.pycharm中运行新建run.py
from scrapy.cmdline import execute
execute(['scrapy', 'crawl', 'cnblogs','--nolog'])