需账号密码登陆的网页爬虫 |
您所在的位置:网站首页 › web账号密码的代码怎么写出来 › 需账号密码登陆的网页爬虫 |
对于普通网页的爬取十分简单,如果网站没有任何反爬机制,只要以下代码就可以实现对于网页的爬取 import requests html = requests.get(url='网址',headers=headers,verify=False) from bs4 import BeautifulSoup soup = BeautifulSoup(html.text,'lxml') #以下三种方式均可对html进行筛选 link = soup.select('div.houseInfo') link = soup.find('div',attrs={'class':'houseInfo'}) links = soup.find_all('td', class_='tdc2')然而有些网页需要账号密码登陆后才可爬取,对于需要登陆的网页爬虫,有以下两种方式: 1.selenium模拟登陆Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE、Mozilla Firefox、Mozilla Suite等。但是此处我们将Selenium用于爬虫的模拟登陆上。 from selenium import webdriver import time driver = webdriver.Firefox() driver.get(登陆界面URL) inputs = driver.find_elements_by_tag_name("input") for input_ in inputs: if input_.get_attribute("type") == "text": input_.send_keys("账号") if input_.get_attribute("type") == "password": input_.send_keys("密码") time.sleep(1) ele_btn = driver.find_element_by_name("submit") ele_btn.click() driver.get(url_yarn) time.sleep(2) html = driver.find_element_by_xpath("//*").get_attribute("outerHTML")爬取html后可用BeautifulSoup进行解析,但是这种方法需要调用浏览器,在无浏览器的情况下无法工作 2.cookie登陆使用账号密码登陆网站后,会生成一个cookie,我们知道得到这个cookie,在请求的时候加到header里面,就可以起到等同于账号密码登陆的效果。 获得cookie的方法 方法1:使用账号密码登陆网页后,火狐浏览器:点击右键-“查看元素”,谷歌浏览器:点击右键-“检查”,其余浏览器也有类似的功能,从报文中可以找到cookie,复制下来即可![]() 由于我要爬取的网页会延迟加载,即请求网页后立马返回的并不包含我需要的数据,只有经过一定等待后才可得到所需的数据,为了解决延迟加载的问题,这里继续使用selenium 。 需要注意以下几点: 为了能在无图形化界面的Linux系统上使用,需要下载PhantomJS,这样就不需要调用浏览器了使用add_cookie添加之前获取的rookie,但之前需get一次url,虽然这里的get没有用,但不执行会报错 from selenium import webdriver import time driver = webdriver.PhantomJS(executable_path=PhantomJS文件路径) driver.get(路径) #虽然这个get没用,但必须要get一下 for dic in cookie_lst: #cookie_lst是之前获取的cookie driver.add_cookie(dic) driver.get(路径) time.sleep(2) html = driver.find_element_by_xpath("//*").get_attribute("outerHTML") from bs4 import BeautifulSoup soup = BeautifulSoup(html,'lxml') link2 = soup.find_all(attrs={'class':'name'}) out = [] for i in link2: out.append(i.text.strip()) print(out) 仍然存在的问题有些网站的cookie是动态的,使用上述方式获取了cookie后,过一段时间cookie便失效了,目前还没有找到解决的方法 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |