etree.HTML()可以用来解析字符串格式的HTML文档对象,将传进去的字符串转变成_Element对象。作为_Element对象,可以方便的使用getparent()、remove()、xpath()等方法。
url = "https://dl.58.com/xiaoqu/150/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/87.0.4280.88 Safari/537.36"
}
rep = requests.get(url, headers=headers)
rep.encoding = 'utf-8'
# print(rep.text) 输出的是网页的全部源代码
html = etree.HTML(rep.text)
# 通过xpath筛选出所需要的代码信息
list_url = html.xpath('//ul[@class="xq-list-wrap"]/li/div[@class="pic"]/a/@href')