python - 如何添加“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”在结果中。
我感谢您的所有帮助。在这里期待与大家一起学习!
非常感谢。
解决方案
您可以使用 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"
推荐阅读
- java - 试图在 listview 中显示 arraylist 让我这个错误无法解析构造函数?
- sql - 复杂模式的 Rails/General SQL 实体属性值
- ruby-on-rails - Rails 在创建动作问题中有许多通过参数
- go - 将 gRPC 拦截器中的请求转换为相关的 protobuf 消息
- c - 有没有办法让 loading() void 在 main() 函数之前开始?
- r - 使用xlsx编写excel文件的for循环?
- php - 将 CSV 文件中的数据插入数据库
- php - 在 PHP中单击时,URL 查询字符串参数未显示在 url中
- ios - 权限问题?无法打开文件 - 文件被禁用
- python - 在“名称”列中仅显示一个名称