4000-520-616
欢迎来到免疫在线!(蚂蚁淘生物旗下平台)  请登录 |  免费注册 |  询价篮
主营:原厂直采,平行进口,授权代理(蚂蚁淘为您服务)
咨询热线电话
4000-520-616
当前位置: 首页 > 新闻动态 >
热卖商品
新闻详情
...请求只拿到script的内容(返回码412) - 灰信网(软件开发博客聚合)
来自 : www.freesion.com/article/93231 发布时间:2021-03-25

最近爬虫遇到一个比较奇怪的现象:
使用send_resquest方法去请求得到html里面body里面只有script,并且打印返回状态码为412(tips:412表示缺失发送时候的先决条件)

请求的代码(请求url:http://www.nhc.gov.cn/zwgk/tian/ejlist.shtml)
\"在这里插入图片描述\"

请求拿到的内容大概是下面这样的
\"!](https://img-blog.csdnimg.cn/20200912091229436.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2RfYXBwZW5k,size_16,color_FFFFFF,t_70#pic_center)\"

后来经过摸索发现可以使用selenium模拟浏览器来绕过那个先决条件,就不会请求只拿到script而是拿到真正的内容.

使用selenium需要安装浏览器驱动,我使用的firfox(也可以chrome网上可搜)。可以参考下面这篇文章进行安装。(这里我个人配置了环境变量还是有点问题,我就在爬的代码(在下面)中browser = webdriver.Firefox(executable_path=“C:\\Program Files\\Mozilla Firefox\\geckodriver.exe”)设置了executable_path,executable_path路径为我的firfox安装路径)https://blog.csdn.net/qq471011042/article/details/79514908

另外还要pip install一些包

from bs4 import BeautifulSoupfrom selenium import webdriverfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import TimeoutExceptionimport selenium.webdriver.support.ui as uifrom lxml import etree

这些都会引用到,放进文件哪个红了下pip install哪个包。

接下来就是实践。
我先把整个能跑的代码贴上

from bs4 import BeautifulSoupfrom selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.common.exceptions import TimeoutExceptionimport selenium.webdriver.support.ui as uifrom lxml import etreebrowser = webdriver.Firefox(executable_path= C:\\Program Files\\Mozilla Firefox\\geckodriver.exe )def is_visible(locator, timeout = 10): try: ui.WebDriverWait(browser, timeout).until(EC.visibility_of_element_located((By.XPATH, locator))) return True except TimeoutException: return Falsebrowser.get( http://www.nhc.gov.cn/zwgk/tian/ejlist.shtml )#browser.get( http://www.nhc.gov.cn/yjb/pqt/new_list.shtml )is_visible( //ul[@ ]//li//h3//a )html = browser.page_source# print(html)content = BeautifulSoup(html, lxml )print(content.encode(\'gbk\'))html1 = etree.HTML(content.encode(\'gbk\'))print(html1)

本文链接: http://elementis412.immuno-online.com/view-751267.html

发布于 : 2021-03-25 阅读(0)
公司介绍
品牌分类
联络我们
服务热线:4000-520-616
(限工作日9:00-18:00)
QQ :1570468124
手机:18915418616