当我使用XPath抓取和解析腾讯公益性的内容时,所有返回的列表都是空的。下面是我的代码(头的信息是隐藏的).And,目标url是https://gongyi.qq.com/succor/project_list.htm#s_tid=75.I,如果有人能帮我解决这个问题,我会很感激的。
import requests
import os
from lxml import etree
if __name__ =='__main__':
url = 'https://gongyi.qq.com/succor/project_list.htm#s_tid=75'
headers = {
'User-Agent': XXX }
response = requests.get(url=url,headers=headers)
page_text = response.text
tree = etree.HTML(page_text)
li_list = tree.xpath('//div[@class="pro_main"]//li')
for li in li_list:
title = li.xpath('./div[2]/div/a/text()')[0]
print(title)
发布于 2021-03-09 11:52:58
因此,这里实际发生的事情是,您只能访问pro_main
div中的第一个pro_main
,因为所有这些li
项及其父项都由JavaScript填充,因此当您用requests.get()
刮html时,您的列表将不存在,它将为空!
好消息是,问题中的JS脚本使用API填充数据,以及网站的具体操作方式,您还可以使用实际的API检索这些标题并打印它们。
import requests, json
import os
if __name__ =='__main__':
url = 'https://ssl.gongyi.qq.com/cgi-bin/WXSearchCGI?ptype=stat&s_status=1&s_tid=75'
resp = requests.get(url).text
resp = resp[1:-1] #Result is wrapped in (), so we get rid of those
jj = json.loads(resp)
for i in jj["plist"]:
title = i["title"]
print(title)
您可以通过打印jj
来探索API,看看您以后是否需要更多的信息!
如果对你有用,请告诉我!
https://stackoverflow.com/questions/66543650
复制相似问题