繁体   English   中英

使用“requests-html”时如何使用绝对链接路径获取原始 html

[英]How to get raw html with absolute links paths when using 'requests-html'

使用requests库向https://stackoverflow.com发出请求时

page = requests.get(url='https://stackoverflow.com')
print(page.content)

我得到以下信息:

<!DOCTYPE html>
    <html class="html__responsive html__unpinned-leftnav">
    <head>
        <title>Stack Overflow - Where Developers Learn, Share, &amp; Build Careers</title>
        <link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196">
        <link rel="apple-touch-icon" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a">
        <link rel="image_src" href="https://cdn.sstatic.net/Sites/stackoverflow/Img/apple-touch-icon.png?v=c78bd457575a"> 
..........

这里的这些源代码有绝对路径,但是当使用带有js渲染requests-html运行相同的URL时

with HTMLSession() as session:
    page = session.get('https://stackoverflow.com')
    page.html.render()
    print(page.content)

我得到以下信息:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>StackOverflow.org</title>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript" src="lib/interface.js"></script>
<script type="text/javascript" src="lib/window.js"></script>
<link href="lib/dock.css" rel="stylesheet" type="text/css" />
<link href="lib/window.css" rel="stylesheet" type="text/css" />
<link rel="icon" type="image/gif" href="favicon.gif"/>
..........

这里的链接是相对路径,

使用带有js渲染requests-html时,如何获取具有绝对路径(如requests )的源代码?

这可能应该是request-html 开发人员的功能请求。 但是现在我们可以通过这个骇人听闻的解决方案来实现这一点:

from requests_html import HTMLSession
from lxml import etree

with HTMLSession() as session:
    html = session.get('https://stackoverflow.com').html
    html.render()

    # iterate over all links
    for link in html.pq('a'):
        if "href" in link.attrib:
            # Make links absolute
            link.attrib["href"] = html._make_absolute(link.attrib["href"])

    # Print html with only absolute links
    print(etree.tostring(html.lxml).decode())

我们通过遍历所有链接并使用 html-object 的私有_make_absolute function 将它们的位置更改为绝对位置来更改 lxml 树下的 html-objects。

此链接中有关模块的文档提到了绝对链接和相对链接之间的区别。

引用:

以绝对形式获取页面上所有链接的列表(不包括锚点):

r.html.absolute_links

你能试试这个说法吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM