Python使用selenium + headless chrome获取网页内容的方法示例
使用python写爬虫时,优选selenium,由于PhantomJS因内部原因已经停止更新,最新版的selenium已经使用headlesschrome替换掉了PhantomJS,所以建议将selenium更新到最新版,使用selenium+headlesschrome
准备工作:
安装chrome、chromedriver、selenium
一、安装chrome
配置yum下载源,在目录/etc/yum.repos.d/下新建文件google-chrome.repo
>cd/ect/yum.repos.d/ >vimgoogle-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
安装googlechrome浏览器:
>yum-yinstallgoogle-chrome-stable
PS:Google官方源可能在中国无法使用,导致安装失败或者在国内无法更新,可以添加以下参数来安装:
>yum-yinstallgoogle-chrome-stable--nogpgcheck
这样,googlechrome即可安装成功。
二、安装chromedriver
查看上述安装的chrome版本,根据版本选择对应的chromedriver下载,下载之后放到/usr/local/bin目录
三、安装selenium
>pipinstallselenium
上述准备工作完成后,就可以开始写代码了
fromselenium.webdriverimportChrome fromselenium.webdriver.chrome.optionsimportOptions 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) #获取返回内容 printbrowser.page_source #查找元素 printbrowser.find_element_by_tag_name('pre').text
备注:如果访问一些详情页有cookie验证,可以先访问主页,然后再访问详情页,webdriver会自动携带cookie
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。