【问题标题】:Modifying scraper code for multiple URLs修改多个 URL 的爬虫代码
【发布时间】:2018-01-09 16:49:41
【问题描述】:

我正在尝试下载同一站点上多个页面上的所有图像。我有一些代码可以从一个页面中抓取所有图像,但无法找到一种简单的方法来让它对多个 URL 重复该过程。

import re
import requests
from bs4 import BeautifulSoup

site = 'SiteNameHere'

response = requests.get(site)

soup = BeautifulSoup(response.text, 'html.parser')
img_tags = soup.find_all('img')

urls = [img['src'] for img in img_tags]

for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)
    with open(filename.group(1), 'wb') as f:
        if 'http' not in url:
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)

【问题讨论】:

  • 将除导入之外的所有代码放在一个函数中,并以 URL 作为参数调用它。
  • for site in [ yoursite1, yoursite2, yoursite3]: 为一个站点做什么?
  • 投票结束 - 这是一件微不足道的事情,而且在 pyhton scape 线程上到处都是如此如何做到这一点。否决:没有研究,没有尝试。

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

我会尝试在 for 循环中添加/更改每个 url 请求。看下面的例子(使用 requests 模块和 lxml):

import lxml.html
import requests

#List of CSID numbers
ListOfNumbers = ['12','132','455']

for CSID in CSIDList:   

     UrlCompleted = ('http://www.chemspider.com/ChemicalStructure.%s.html?rid' %CSID)
     ChemSpiderPage = requests.get(UrlCompleted)
     html = lxml.html.fromstring(ChemSpiderPage.content)
     #Xpath describing the location of the string (see "text()" at the end)
     MolecularWeight = html.xpath('//*[@id="ctl00_ctl00_ContentSection_ContentPlaceHolder1_RecordViewDetails_rptDetailsView_ctl00_structureHead"]/ul[1]/li[2]/text()')

          try:
               print (CSID, MolecularWeight)
               print (MolecularWeight)   
          except:
               print 'ERROR'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多