首页 > 解决方案 > 如何本地化为我提供 url 的正确 xpath?

问题描述

我正在尝试通过 python 抓取一些 URL。特别是,我正在研究与香港选举平台的链接。我使用了chrome提供的inspect功能,在python上也使用了lxml的etree功能。我已经找到了“文本”的 xpath。

我使用的代码是

 def extract_info_urls(self, response):
        raw_tree = etree.HTML(response)
        platform_urls = raw_tree.xpath('//*[@id="table-district-member"]/tbody/tr/td[6]/div/a/@href|//*[@id="table-district-member"]/tbody/tr/td[4]/div/a/@href')
        return platform_urls

结果如下所示:

../../pdf/intro_to_can/A01_1_ENG.html

综上所述,我的谦虚问题是如何获得完整的网址 - https://www.elections.gov.hk/dc2019/pdf/intro_to_can/A01_1_ENG.html - 而不仅仅是以“.. /../pdf”在结果中。

这是我在这里的第一个问题,可能很愚蠢。但我感谢你的所有帮助。在这里期待与大家一起学习!

非常感谢你。

标签: pythonhtmlurlxpath

解决方案


要获取完整的 URL,您可以替换

return platform_urls

return ["https://www.elections.gov.hk/dc2019/" + platform_url.lstrip("../..") for platform_url in platform_urls]

推荐阅读