Python使用selenium + headless chrome获取网页内容的方法示例
2019-10-16 18:07
1451 查看
使用python写爬虫时,优选selenium,由于PhantomJS因内部原因已经停止更新,最新版的selenium已经使用headless chrome替换掉了PhantomJS,所以建议将selenium更新到最新版,使用selenium + headless chrome
准备工作:
安装chrome、chrome driver、selenium
一、安装chrome
配置yum下载源,在目录/etc/yum.repos.d/
下新建文件google-chrome.repo
> cd /ect/yum.repos.d/ > vim google-chrome.repo
编辑google-chrome.repo
,内容如下,保存退出
[google-chrome] name=google-chrome baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch enabled=1 gpgcheck=1 gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
安装google chrome浏览器:
> yum -y install google-chrome-stable
PS: Google官方源可能在中国无法使用,导致安装失败或者在国内无法更新,可以添加以下参数来安装:
> yum -y install google-chrome-stable --nogpgcheck
这样,google chrome即可安装成功。
二、安装chrome driver
查看上述安装的chrome版本,根据版本选择对应的chrome driver下载,下载之后放到/usr/local/bin目录
三、安装selenium
> pip install selenium
上述准备工作完成后,就可以开始写代码了
from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument('lang=zh_CN.UTF-8') # 在linux上需要添加一下两个参数 options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') browser = Chrome(chrome_options=options) browser.set_page_load_timeout(30) browser.set_script_timeout(30) browser.get(url) # 获取返回内容 print browser.page_source # 查找元素 print browser.find_element_by_tag_name('pre').text
备注:如果访问一些详情页有cookie验证,可以先访问主页,然后再访问详情页,webdriver会自动携带cookie
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- Python获取网页指定内容(BeautifulSoup工具的使用方法)
- Python获取网页指定内容(BeautifulSoup工具的使用方法)
- Python获取基金网站网页内容、使用BeautifulSoup库分析html操作示例
- JavaScript使用正则表达式获取全部分组内容的方法示例
- python使用htmllib分析网页内容的方法
- python获取完整网页内容(即包括js动态加载的):selenium+phantomjs
- Python开发中爬虫使用代理proxy抓取网页的方法示例
- 当file_get_contents获取不到网页内容时,以下方法可使用
- python+selenium调用chrome打开网址获取内容
- python selenium 获取标签的属性值、内容、状态方法
- Python使用正则表达式抓取网页图片的方法示例
- Python获取动态网页内容的一种处理方法
- python使用selenium提取script节点的内容不成功的解决方法
- 在python使用selenium获取动态网页信息并用BeautifulSoup进行解析--动态网页爬虫
- 使用Python+selenium获取tag_element标签输入内容出现错误
- python爬虫,selenium使用,Firefox-chrome-IE问题解决方法,selenium的基本操作
- 当file_get_contents获取不到网页内容时,以下方法可使用
- php使用fsockopen函数发送post,get请求获取网页内容的方法
- python打开网页获取网页内容方法总结
- python打开网页获取网页内容方法总结