headers = { 'User-Agent': random.choice(user_agent_list) } # print(headers) # for page in range(11,84): url = f'http://www.chinawuliu.com.cn/zcms/ui/catalog/15196/pc/index_11.shtml' # url = 'http://www.chinawuliu.com.cn/zixun/hgjj/' response = requests.get(url=url,proxies=get_proxies(),headers=headers,timeout=8) response.encoding = 'utf-8' # 解析请求 etree = html.fromstring(response.text) info_url = etree.xpath('/html/body/main/div/div[1]/div[3]/ul/li/p[1]/a/@href') t_url = [f"http://www.chinawuliu.com.cn{t_url}" for t_url in info_url] for detail_url in t_url: res = requests.get(url=detail_url, headers=headers,proxies=get_proxies(),timeout=5) res.encoding = 'utf-8' tree = html.fromstring(res.text) name = tree.xpath('/html/body/main/div/div[1]/div[1]/span/text()') print(name)这个代码为什么不输出name就结束进程了
时间: 2024-04-25 08:27:17 浏览: 15
你的代码看起来没有什么问题,可以正常输出name。可能是因为你在运行代码时,没有获取到符合条件的数据,导致输出为空。你可以在for循环外面添加一个判断,判断是否获取到了name,如果获取到了就输出,否则提示没有获取到数据。具体来说,你可以这样修改代码:
```
headers = { 'User-Agent': random.choice(user_agent_list) }
url = f'http://www.chinawuliu.com.cn/zcms/ui/catalog/15196/pc/index_11.shtml'
response = requests.get(url=url,proxies=get_proxies(),headers=headers,timeout=8)
response.encoding = 'utf-8'
etree = html.fromstring(response.text)
info_url = etree.xpath('/html/body/main/div/div[1]/div[3]/ul/li/p[1]/a/@href')
t_url = [f"http://www.chinawuliu.com.cn{t_url}" for t_url in info_url]
for detail_url in t_url:
res = requests.get(url=detail_url, headers=headers,proxies=get_proxies(),timeout=5)
res.encoding = 'utf-8'
tree = html.fromstring(res.text)
name = tree.xpath('/html/body/main/div/div[1]/div[1]/span/text()')
if name:
print(name)
else:
print('没有获取到数据')
```
这样可以更清晰地判断是否获取到了数据。