• 爬取大众点评地址数据


     如下图是我们要爬取的数据

     因为要爬取所有的地址数据,所以我们要将 更多 点开。这就涉及js操作,需要使用selenium模块。
     

    找到每个更多,然后点开。

    # 点击更多,将未显示的地址暴露出来
        more_click = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'fn-more')))
        for  a in more_click:
            a.click()

    当所有的更多都被点开后,光标已经挪动到了最底层的位置,这时需要我们将光标再返回到顶部。
    点击返回顶部的按钮。

    #点击回到顶部,从头开始爬取数据
        to_top = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'toTop')))
        to_top.click()

    然后再开始一级一级的爬取数据。

     

    完整版代码

    考虑到性能,所以是使用了协程gevent模块。

     1 from selenium import webdriver
     2 from selenium.webdriver.common.by import By
     3 from selenium.webdriver.support.ui import WebDriverWait
     4 from selenium.webdriver.support import expected_conditions as EC
     5 import gevent
     6 
     7 
     8 browser = webdriver.Ie('E:python_serverIEDriverServer')
     9 wait = WebDriverWait(browser, 10)
    10 
    11 browser.get("https://www.dianping.com/citylist/citylist?citypage=1")
    12 
    13 def main():
    14 
    15     # 点击更多,将未显示的地址暴露出来
    16     more_click = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'fn-more')))
    17     for  a in more_click:
    18         a.click()
    19 
    20     #点击回到顶部,从头开始爬取数据
    21     to_top = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, 'toTop')))
    22     to_top.click()
    23 
    24     #地区
    25     adress = browser.find_elements_by_class_name('vocabulary')
    26     for  i in adress:
    27         print(i.text)
    28 
    29     #直辖市,港澳台
    30     adress_city_name_1 = browser.find_elements_by_class_name('terms')
    31     for i in adress_city_name_1:
    32         print(i.text)
    33 
    34     #地级市,县级市
    35     adress_city_name_2 = browser.find_elements_by_class_name('terms-open')
    36     for i in adress_city_name_2:
    37         print(i.text)
    38 
    39     browser.close()
    40 
    41 if __name__ == '__main__':
    42     gevent.joinall([
    43             gevent.spawn(main),
    44         ])
    View Code

    结果部分截图

  • 相关阅读:
    03.移除相同的元素
    02.计算数组元素之和
    01-找出元素在数组中的位置
    node.js中Content-Type的设置
    node.js接受form表单数据
    node.js创建服务器
    mongoDB笔记
    TDK三大标签SEO(搜索引擎优化)优化
    引入网页图标
    JavaScript实现二叉搜索树
  • 原文地址:https://www.cnblogs.com/lixiaoliuer/p/7324876.html
Copyright © 2020-2023  润新知