|-转 python获取完整网页内容(含js动态加载的):selenium+phantomjs
https://blog.csdn.net/huwei2003/article/details/107490468 建议安装pip install Selenium4R Selenium4R是 Selenium4的魔改版,国内可以直接安装
1 不管用requests_html,还是获取网页的源码时,发现通过ajax动态加载的内容都获取不到,得通过分析动态加载的接口去重新请求数据,有时很不方便。
2 下面我们利用 +phantomjs 来实现一次性获取网页上所有的内容;
1. 下载Phantomjs,下载地址:https://phantomjs.org/download.html 选择下载windows的还是linux的 2. 下完之后直接解压就OK了,然后selenium的安装用pip就行了
代码:
import requests from lxml import etree from lxml import html from html.parser import HTMLParser #导入html解析库 from selenium import webdriver import time def getHTMLText(url): driver = webdriver.PhantomJS(executable_path='E:\\pythontest\\phantomjs-2.1.1-windows\\bin\\phantomjs') # phantomjs的绝对路径 time.sleep(2) driver.get(url) # 获取网页 time.sleep(2) return driver.page_source def getHtmlByXpath(html_str,xpath): strhtml = etree.HTML(html_str) strResult = strhtml.xpath(xpath) return strResult def w_file(filepath,contents): with open(filepath,'w',encoding='gb18030') as wf: wf.write(contents) def main(): url = 'https://m.fygdrs.com/h5/news.html?t=2&id=67062' #要访问的网址 strhtml = getHTMLText(url) #获取HTML #print(html) w_file('E:\\pythontest\\wfile.txt',strhtml) strDiv=getHtmlByXpath(strhtml,"//div[@id='Article-content']") if(strDiv): str1= html.tostring(strDiv[0]) print(str1) str2 = HTMLParser().unescape(str1.decode()) print(str2) w_file('E:\\pythontest\\wfile3.txt',str2) print('ok') if __name__ == '__main__': main()
--- end --- ...
浏览更多内容请先登录。
立即注册
分享的网址网站均收集自搜索引擎以及互联网,非查问网运营,查问网并没有提供其服务,请勿利用其做侵权以及违规行为。
更新于:2023-12-10 19:47:52
相关内容
python代码整理(2022年4月-2024年3月)
Python和PHP获取百度url跳转的真实地址代码(2022年4月实测有效)
Pip/python-如何查看已安装的包有哪些版本?如何查看某个包存在哪些版本?pip...
用undetected_chromedriver代替selenium解决浏览器打不开网页
sublime text下 Python 问题:TabError: inconsistent use of tabs and s...
php获取链接跳转的真实地址
PHP向js传数组
js关于对齐方式display的三个属性
Python的扩展和模块安装时遇到的问题整理
windows环境下python3安装Crypto扩展
pip install 报错 ERROR: Can not execute setup.py since setuptools i...
运行python -V 报错 -bash: python: command not found
protobuf requires Python ‘>=3.7‘ but the running Python is 3.6.5的解...
推荐内容