当前位置:   article > 正文

python脚本爬虫_pypi 爬虫脚本

pypi 爬虫脚本

环境:

ubuntu18.04、python3.7

python脚本:

import os
import re
import time
from selenium import webdriver
from bs4 import BeautifulSoup
from urllib.request import urlretrieve
 
def selelnium_test(url, save_path, num):
    driver = webdriver.Chrome()
    driver.get(url)
 
    for i in range(num):
        driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        time.sleep(1)
    html = driver.page_source
    bsObj = BeautifulSoup(html)
    find_imgs = bsObj.findAll("img", {'src': re.compile(r'http[^\s]*')})
    print(find_imgs)
    i = 1
    for img in find_imgs:
        imgurl = img.attrs['src']
        path = os.path.join(save_path, "%s.jpg" % i)
        urlretrieve(imgurl, path)
        print("正在下载第{}张图片".format(i))
        i += 1
    driver.quit()
 
 
if __name__ == '__main__':
    # 搜索的网页
    url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1608712803138_R&pv=&ic=&nc=1&z=&hd=&latest=&copyright=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&sid=&word=%E7%81%AB%E7%81%BE%E7%8E%B0%E5%9C%BA'
    # 图片存放地址
    save_path = "火灾"
    # 搜索的页数
    num = 50
 
    if not os.path.exists(save_path):
        os.mkdir(save_path)
 
    selelnium_test(url, save_path, num)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

问题及解决

1.报错:ModuleNotFoundError: No module named ‘selenium’
解决方案:pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple

2.报错:ModuleNotFoundError: No module named ‘bs4’
解决方案:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple beautifulsoup4

3.报错:Message: ‘chromedriver’ executable needs to be in PATH
解决方案: 主要的原因还是因为selenium模拟的客户端对浏览器的操作,但相应浏览器的驱动版本不匹配导致的。为了解决这个问题,我们需要先了解我们当前浏览器的版本。以小菌用的谷歌浏览器为例。打开浏览器,在地址栏输入chrome://version/便可以查看到谷歌当前的版本号。
点击chromedriver下载相对自己Google Chromelinux版本的,然后解压,得到一个chromedriver。然后复制到sudo cp chromedriver /usr/bin/,给权限,不给会出错。

sudo chmod 777 chromedriver
  • 1

这里/usr/bin都是我安装chromedriver和Python的目录,根据自己的安装地方移动。如果Google Chrome和Python安装在不同的地方,那就要移动两次。

或者是直接引用目录路径

brower = webdriver.Firefox(executable_path=r'/usr/local/Cellar/geckodriver/0.21.0/bin/geckodriver')
brower = webdriver.Chrome(executable_path=r'/usr/local/Cellar/geckodriver/0.21.0/bin/geckodriver')
  • 1
  • 2

windows平台直接引用

driver = webdriver.Chrome(r"E:\projection\crawler\chromedriver.exe")
  • 1

有了这个脚本,相信你能很快上手爬虫。

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/1004934
推荐阅读
相关标签
  

闽ICP备14008679号