|-转 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
相关内容
php获取链接跳转的真实地址
PHP向js传数组
python 学习中遇到的问题整理
没有使用asynccontextmanager ,但是报cannot import name 'asynccontextman...
python3.10.0+pyinstaller4.7打包,IndexError: tuple index out of range...
error: Microsoft Visual C++ 14.0 or greater is required.
安装conda搭建python环境(保姆级教程)
学习飞浆过程中遇到“缺少paddle.fluid”
[NLP实践01]simpletransformers安装和文本分类简单实现
primeqa 安装requirements时报错
sublime text下 Python 问题:TabError: inconsistent use of tabs and s...
uiautomation报错 No module named 'comtypes.stream' Can not load UIA...
解决无法加载UIAutomationCore.dll的报错
汉字目标点选识别-ddddocr(返回识别的内容和位置)
python 常用命令
opencv报错及解决:AttributeError: module ‘cv2‘ has no attribute ‘...
AttributeError: module 'cv2.cv2' has no attribute 'cv'
sublime text常用快捷键及多行列模式批量操作教程
python配置opencv环境后,读取图片,报错:can‘t open/read file: check f...
各种服务器通用搭建python训练模型用的环境,以训练SoloSpeech为列子
python的selenium的用法整理
selenium3定位元素(包括父子,兄弟)及常见操作
使用Selenium自动验证滑块登录
nodejs puppeteer 自动化测试和采集的内容整理
[Bug]: TypeError: page.$x is not a function
推荐内容