最近爬虫遇到一个比较奇怪的现象:
使用send_resquest方法去请求得到html里面body里面只有script,并且打印返回状态码为412(tips:412表示缺失发送时候的先决条件)
请求的代码(请求url:http://www.nhc.gov.cn/zwgk/tian/ejlist.shtml)
请求拿到的内容大概是下面这样的
后来经过摸索发现可以使用selenium模拟浏览器来绕过那个先决条件,就不会请求只拿到script而是拿到真正的内容.
使用selenium需要安装浏览器驱动,我使用的firfox(也可以chrome网上可搜)。可以参考下面这篇文章进行安装。(这里我个人配置了环境变量还是有点问题,我就在爬的代码(在下面)中browser = webdriver.Firefox(executable_path=“C:\Program Files\Mozilla Firefox\geckodriver.exe”)设置了executable_path,executable_path路径为我的firfox安装路径)https://blog.youkuaiyun.com/qq471011042/article/details/79514908
另外还要pip install一些包
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selen