为什么下面一个xapth取不到内容返回的是一个空的列表,
但是xpath是正确的啊
import requests
import os
from lxml import etree
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/527.36 (KHTML, like Gecko)'
' Chrome/96.0.8664.55 Safari/537.36 Edg/56.0.054.43'}
picture_e = 'picture_e'
if not os.path.exists(picture_e):
os.mkdir(picture_e)
url = 'https://www.vilipix.com/tags/%E5%A5%B3%E3%81%AE%E5%AD%90/illusts'
fn_q = requests.get(url, headers=headers)
html_q = fn_q.text
dy_q = etree.HTML(html_q)
fn_li_q = dy_q.xpath('//*[@class="illust"]//img/@alt')
print(fn_li_q)
C:\Users\21905\Documents\PythonProject\reptile\venv\Scripts\python.exe
[]
进程已结束,退出代码为 0
xpath定位我写过几个代码有时候有用有时候没用,感觉就特别玄学。
得到网页图片下的名字
你这个网页中的内容是通过js代码读取外部json数据来动态更新的。
requests只能获取网页的静态源代码,动态更新的内容取不到。
对于动态更新的内容要用selenium 来爬取。
或者是通过F12控制台分析页面数据加载的链接,找到真正json数据的地址进行爬取。
在页面上点击右键,右键菜单中选 "查看网页源代码"。
你题目的解答代码如下:
from selenium import webdriver
import time
import os
from lxml import etree
url = 'https://www.vilipix.com/tags/%E5%A5%B3%E3%81%AE%E5%AD%90/illusts'
driver = webdriver.Chrome()
driver.get(url)
time.sleep(3)
html_q = driver.page_source
dy_q = etree.HTML(html_q)
fn_li_q = dy_q.xpath('//*[@class="illust"]//img/@alt')
print(fn_li_q)
如有帮助,望采纳!谢谢!