Python 修改多个URL的代码

Python 修改多个URL的代码,python,web-scraping,beautifulsoup,python-requests,Python,Web Scraping,Beautifulsoup,Python Requests,我正在尝试下载同一站点上几个页面上的所有图像。我有一些代码可以从一个页面获取所有图像,但无法找到一种简单的方法让它对几个URL重复这个过程 import re import requests from bs4 import BeautifulSoup site = 'SiteNameHere' response = requests.get(site) soup = BeautifulSoup(response.text, 'html.parser') img_tags = soup.fi

我正在尝试下载同一站点上几个页面上的所有图像。我有一些代码可以从一个页面获取所有图像,但无法找到一种简单的方法让它对几个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)

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


将除导入之外的所有代码放在一个函数中,并使用URL作为参数调用它。
对于[yoursite1,yoursite2,yoursite3]中的站点:
为一个站点做什么?投票关闭-这是一件非常琐碎的事情,pyhton scape线程上有很多线程,因此如何做到这一点。否决票:不研究,不尝试。
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'