爬虫的一些东西

解析html网页

beautifulsouplxml都是基于xpath语法解析xml或者html

beautifulsoup

官方文档https://beautifulsoup.readthedocs.io/zh_CN/v4.4.0/#
beautifulsoup可以选择解析器后端,解析成对象,通过.访问
安装

pip install beautifulsoup4

构造解析器

from bs4 import BeautifulSoup
BeautifulSoup(markup, "html.parser")
BeautifulSoup(markup, "lxml")

lxml

只能基于xpath语法https://www.w3school.com.cn/xpath/index.asp
安装

pip install lxml

基础使用

from lxml import  etree
html=etree.parse('xx.html',etree.HTMLParser())
aa=html.xpath('//*[@id="s_xmancard_news"]/div/div[2]/div/div[1]/h2/a[1]/@href')
print(aa)

rep=requests.get('https://www.baidu.com')
html=etree.HTML(rep.text)
aa=html.xpath('//*[@id="s_xmancard_news"]/div/div[2]/div/div[1]/h2/a[1]/@href')
print(aa)

解析json数据

可以使用jsonpath库,解析json数据成对象,然后通过.访问
JsonPath完全介绍及详细使用教程

模拟浏览器操作(自动化测试)

selenium

安装

pip install selenium

自行下载对应浏览器的webdriver,
微软edge浏览器的 msedgedriver.exe 放入系统环境变量PATH

from bs4 import BeautifulSoup        # 用于解析网页源代码的模块
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Edge()
link = "https://music.163.com/#/search/m/?s=" + search_name + "&type=1"  # 要搜索的链接
driver.get(link)
iframe_elemnt = driver.find_element(By.ID, "g_iframe")  # 因为直接获取不到iframe的内容,因此使用web_driver
driver.switch_to.frame(iframe_elemnt)  # 关键步骤,跳转到iframe里面,就可以获取HTML内容
soup = BeautifulSoup(driver.page_source, "html.parser")  # 通过 BeautifulSoup 模块解析网页,具体请参考官方文档。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值