什么时候最好使用bs4
如果需求是要求解析出携带html标签的局部数据 例如 li p div
这样带有标签符号的html文本 那就使用bs4解析。
使用bs4, bs4在实现标签定位的时候返回的直接就是定位到标签对应的字符串数据
xpath如何更加具有通用性
xpath表达式中使用管道符分割的作用 可以表示管道符左右两侧的子xpath表达式同时生效或者一个生效
例子 将https://www.aqistudy.cn/historydata/ 所有的 城市名称解析出来
from lxml import etree
import requests
headers {
User-Agent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36
url https://www.aqistudy.cn/historydata/
page_text requests.get(url url, headers headers)
tree etree.HTML(page_text.text)
正常解析写法
# 热门城市 hot_cities tree.xpath( //div[ class bottom ]/ul/li/a/text() ) # 全部城市 all_cities tree.xpath( //div[ class bottom ]/ul/div[2]/li/a/text() )
管道符解析写法:
# 热门 全部城市 cities tree.xpath( //div[ class bottom ]/ul/li/a/text() | //div[ class bottom ]/ul/div[2]/li/a/text() )



