使用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, & 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">
..........
这里的这些源代码有绝对路径,但当使用requests-html
和js渲染运行相同的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
这样具有绝对路径的源代码?
这可能是请求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对象的私有_make_absolute
函数将其位置更改为绝对,来更改lxml树下的html对象。
此链接中的模块文档提到了绝对链接和相对链接之间的区别。
报价:
获取页面上所有链接的列表,以绝对形式(锚除外(:
r.html.absolute_links
你能试试这个说法吗?