抓取动态网页(我爱我家的网页中(1.)学习过程分析)

优采云 发布时间: 2021-10-01 03:24

  抓取动态网页(我爱我家的网页中(1.)学习过程分析)

  对于web页面上的某些内容,需要进行某些交互操作才能获取相应的数据,例如常见的Ajax请求。为了抓取Ajax请求的结果,可以通过Ajax请求的URL抓取返回的结果,也可以使用selenium模块模拟网页Ajax。简单地记录一个学习过程

  1.问题分析

  例如,在下面的我爱我的主页()中,当您在搜索框中输入“保险”时,后台将自动发送Ajax请求,以获取收录“保险”一词的所有单元格名称

  

  通过网络分析,您可以看到Ajax请求返回了一个JSON对象:

  

  2.抓取数据

  2.1使用请求

  构造Ajax请求的URL,并分析使用Ajax请求获得的JSON数据。代码如下:

  #coding:utf-8

import requests

import json

from lxml import html

url="https://wh.5i5j.com/ajaxsearch?status=ershoufang&keywords=%s"%(u'恒')

response = requests.get(url,headers={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; r…) Gecko/20100101 Firefox/64.0"})

html_string = json.loads(response.text)['res']

tree = html.fromstring(html_string)

li_tags=tree.getchildren()

house_info={}

for tag in li_tags:

name = tag.xpath('.//div/span[@class="name"]/text()')[0]

count = tag.xpath('.//span[@class="tao"]/text()')[0]

print name,count

house_info[name]=count

# print house_info

  2.2使用硒

  Selenium可以模拟浏览器的行为,因此它可以用作爬虫程序(但速度较慢),以模拟浏览器对网站

  安装selenium:PIP安装selenium

  (下载浏览器驱动程序:首次使用selenium时,您可能会报告错误mon.exceptions.webdriverexception,因为您需要下载驱动程序和模拟浏览器的下载地址)

  硒的使用参考:

  使用selenium捕获上述数据的代码如下:

  from selenium import webdriver

driver = webdriver.Firefox(executable_path='D:\\Python\\geckodriver.exe') #路径为下载的浏览器驱动保存路径

driver.get('https://wh.5i5j.com/zufang/') #打开网页

kw = driver.find_element_by_id("zufang") #找到搜索框

kw.send_keys(u"万") #搜索框中输入文字 “万”

# button = driver.find_element_by_class_name("btn-search")

# button.click()

driver.implicitly_wait(30) #隐式等待30秒,浏览器查找每个元素时,若未找到会等待30s,30s还未找到时报错

li_tags = driver.find_elements_by_css_selector('ul.search_w li') #注意此处是find_elements, 复数查找多个element

for li_tag in li_tags:

name = li_tag.find_element_by_class_name('name').text

count = li_tag.find_element_by_class_name('tao').text

print name, count

  在上面的代码中,因为Ajax请求需要时间来完成,所以需要一个驱动程序。隐式等待(30)使浏览器隐式等待30秒,也就是说,当浏览器找到每个元素时,如果找不到它,它将等待30秒,如果30秒后找不到它,将报告错误

  关于selenium的等待,有显示等待和隐式等待

  显示等待:指定等待元素出现或条件为真的时间,如以下代码所示:

  newWebDriverWait(driver,15).until(

ExpectedConditions.presenceOfElementLocated(By.cssSelector("css locator")));

  隐式等待:全局,对所有元素都有效。如果找不到元素,它将等待设置的时间,例如驱动程序。隐式等待(30)

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线