Skip to main content
 首页 » 编程设计

python之使用 Python 请求提取 href URL

2025年05月04日29jpfss

我想使用 python 中的请求包从 xpath 中提取 URL。我可以得到文本,但我没有尝试提供 URL。谁能帮忙?

ipdb> webpage.xpath(xpath_url + '/text()') 
['Text of the URL'] 
ipdb> webpage.xpath(xpath_url + '/a()') 
*** lxml.etree.XPathEvalError: Invalid expression 
ipdb> webpage.xpath(xpath_url + '/href()') 
*** lxml.etree.XPathEvalError: Invalid expression 
ipdb> webpage.xpath(xpath_url + '/url()') 
*** lxml.etree.XPathEvalError: Invalid expression 

我使用本教程开始:http://docs.python-guide.org/en/latest/scenarios/scrape/

看起来应该很容易,但在我的搜索过程中没有任何结果。

谢谢。

请您参考如下方法:

您是否尝试过 webpage.xpath(xpath_url + '/@href')?

完整代码如下:

from lxml import html 
import requests 
 
page = requests.get('http://econpy.pythonanywhere.com/ex/001.html') 
webpage = html.fromstring(page.content) 
 
webpage.xpath('//a/@href') 

结果应该是:

[ 
  'http://econpy.pythonanywhere.com/ex/002.html', 
  'http://econpy.pythonanywhere.com/ex/003.html',  
  'http://econpy.pythonanywhere.com/ex/004.html', 
  'http://econpy.pythonanywhere.com/ex/005.html' 
]