爬虫--python3.6+selenium+BeautifulSoup实现动态网页的数据抓取,适用于对抓取频率不高的情况

说在前面: 本文主要介绍如何抓取 页面加载后需要通过JS加载的数据和图片

本文是通过python中的selenium(pyhton包) + chrome(谷歌浏览器) + chromedrive(谷歌浏览器驱动)

chrome 和chromdrive建议都下最新版本(参考地址:https://blog.csdn.net/yoyocat915/article/details/80580066)

同样支持无头模式(不需要打开浏览器)

直接上代码:site_url:需要爬取的地址,CHROME_DRIVER_PATH:chromedrive存放地址

def get_dynamic_html(site_url):
    print('开始加载',site_url,'动态页面')
    chrome_options = webdriver.ChromeOptions()
    #ban sandbox
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    #use headless,无头模式
    chrome_options.add_argument('--headless')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--ignore-ssl-errors')
    driver = webdriver.Chrome(executable_path=CHROME_DRIVER_PATH,chrome_options=chrome_options)
    #print('dynamic laod web is', site_url)
    driver.set_page_load_timeout(100)
    #driver.set_script_timeout(100)
    try:
        driver.get(site_url)
    except Exception as e:
        #driver.execute_script('window.stop()')  # 超出时间则不加载
        print(e, 'dynamic web load timeout')
    data = driver.page_source
    soup = BeautifulSoup(data, 'html.parser')
    try:
        driver.quit()
    except:
        pass
    return soup

返回的一个soup,这样可以对这个soup进行搜索节点,使用select,search,find等方法找到你想要的节点或者数据

同样如果你想变成文本下载下来,则

try:
        with open(xxx.html, 'w+', encoding="utf-8") as f:
            #print ('html content is:',content)
            f.write(get_dynamic_html('https://xxx.com').prettify())
            f.close()
    except Exception as e:
        print(e)

下面详细说一下,beautifusoup的搜索

首先如何定位到一个标签

1.使用 find  (这位博主详细介绍了https://www.jb51.net/article/109782.htm)

  • find() 返回匹配第一个:如soup.find(name='ul',attrs={class:'hh'}) 返回第一个 class='hh'的ul
  • find_all() 返回全部
  • find_parent() 搜索父标签,返回第一个
  • find_parents()搜索父标签,返回全部
  • find_next_sibling()返回下一个同级标签
  • find_next_siblings()
  • find_previous_sibling() 返回上一个同级标签
  • find_previous()返回前面的标签
  • find_all_previous()
  • find_next()返回后面的标签
  • find_all_next()
2.使用select
 通过标签名,类名,id 类似 Jquery的选择器 如 soup.select('p .link #link1') 选择定位到 <p class='link' id='link1'></p>
 
通过属性查找 ,如href ,title,link等属性,如  soup.select('p a[href="http://example.com/elsie"]')
这里匹配到的是最小的 <a href='http://example.com/elsie'></a> 并且他的上级为<p></p>
 
最后通过beautifusoup是筛选元素的一种好的方法,下篇我们介绍正则表达式匹配筛选 爬虫内容
 
 

猜你喜欢

转载自www.cnblogs.com/lelexiu/p/10189747.html
今日推荐