请注意:这个问题可以通过使用selenium库轻松解决,但我不想使用selenium,因为主机没有安装浏览器,也不愿意。
重要:我知道render()会在第一时间下载chromium,我对此很满意。
问:我怎么能得到页面源时,它是由JS代码生成的?例如这台HP打印机:
220.116.57.59
有人在网上发帖建议使用:
from requests_html import HTMLSession
r = session.get('https://220.116.57.59', timeout=3, verify=False)
session = HTMLSession()
base_url = r.url
r.html.render()
但是打印r.text
不会打印完整的页面源代码,并且表明JS被禁用:
<div id="pgm-no-js-text">
<p>JavaScript is required to access this website.</p>
<p>Please enable JavaScript or use a browser that supports JavaScript.</p>
</div>
原答案:https://stackoverflow.com/a/50612469/19278887(最后一部分)
获取配置端点,然后解析XML以获取所需的数据。
例如:
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0"
}
with requests.Session() as s:
soup = (
BeautifulSoup(
s.get(
"http://220.116.57.59/IoMgmt/Adapters",
headers=headers,
).text,
features="xml",
).find_all("io:HardwareConfig")
)
print("n".join(c.find("MacAddress").getText() for c in soup if c.find("MacAddress") is not None))
输出:
E4E749735068
E4E74973506B
E6E74973D06B