首页 > 解决方案 > 如何添加“https://www.” 使用 python 进入你的抓取结果?

问题描述

我正在尝试通过 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 ["https://www.elections.gov.hk/dc2019/" + platform_url.lstrip("../..") for platform_url in platform_urls]

结果如下所示:

../../pdf/intro_to_can/A01_1_ENG.html
../../pdf/intro_to_can/A01_2_ENG.html
../../pdf/intro_to_can/A02_1_ENG.html

...

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

我感谢您的所有帮助。在这里期待与大家一起学习!

非常感谢。

标签: pythonhtmlurlweb-scrapingxpath

解决方案


您可以使用 urljoin():

from urllib.parse import urljoin

scraped_url = "https://www.elections.gov.hk/dc2019/eng/intro_to_can/A.html"
pdf_url = "../../pdf/intro_to_can/A01_1_ENG.html"

full_url = urljoin(scraped_url, pdf_url)

应该给出一个输出

"https://www.elections.gov.hk/dc2019/pdf/intro_to_can/A01_1_ENG.html"

推荐阅读