解决一下以下代码报错的import requests from lxml import etree url = 'https://www.shanghairanking.cn/institution' headers = { 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } res = requests.get(url=url,headers=headers) print(res.status_code) html = etree.HTML(res.text) lis = html.xpath("//*[@id="__layout"]/div/div[2]/div[2]/div[1]") print(len(lis))
时间: 2024-03-26 17:37:00 浏览: 160
from lxml import etree
这段代码有一个小错误,就是在xpath的语句中双引号没有转义,需要改成单引号。修改后的代码如下:
```python
import requests
from lxml import etree
url = 'https://www.shanghairanking.cn/institution'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
res = requests.get(url=url, headers=headers)
print(res.status_code)
html = etree.HTML(res.text)
lis = html.xpath('//*[@id="__layout"]/div/div[2]/div[2]/div[1]')
print(len(lis))
```
这样就可以正确运行了,输出页面中指定元素的数量。
阅读全文