解析html网页
beautifulsoup
和lxml
都是基于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 模块解析网页,具体请参考官方文档。