【问题标题】:How to scrape images from a aspx page?如何从 aspx 页面中抓取图像?
【发布时间】:2016-09-20 11:06:20
【问题描述】:

我正在尝试从 aspx 页面 scrape 图片即使在阅读了几个线程之后也无法弄清楚如何做到这一点这是原始代码

from bs4 import BeautifulSoup as bs
import urlparse
import urllib2
from urllib import urlretrieve
import os
import sys
import subprocess
import re


def thefunc(url, out_folder):

    c = False

我已经定义了 aspx 页面的标题和一个区分普通页面和 aspx 页面的 if 语句

    select =  raw_input('Is this a .net  aspx page ? y/n : ')
    if select.lower().startswith('y'):
        usin = raw_input('Specify origin of .net page : ')
        usaspx = raw_input('Specify aspx page url : ')

aspx 页面的标题

        headdic = {
            'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Origin': usin,
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': usaspx,
            'Accept-Encoding': 'gzip,deflate,sdch',
            'Accept-Language': 'en-US,en;q=0.8',
            'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
        }
        c = True

    if c:
        req = urllib2.Request(url, headers=headic)
    else:
        req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
    resp = urllib2.urlopen(req)
    
    soup = bs(resp, 'lxml')
    
    parsed = list(urlparse.urlparse(url))

    print '\n',len(soup.findAll('img')), 'images are about to be downloaded'

    for image in soup.findAll("img"):
        
        print "Image: %(src)s" % image
        
        filename = image["src"].split("/")[-1]
        
        parsed[2] = image["src"]
        
        outpath = os.path.join(out_folder, filename)

        try:
        
            if image["src"].lower().startswith("http"):
                urlretrieve(image["src"], outpath)
            else:
                urlretrieve(urlparse.urlunparse(parsed), outpath)
        except:
            print 'OOPS missed one for some reason !!'
            pass


try:
    put =  raw_input('Please enter the page url : ')
    reg1 = re.compile('^http*',re.IGNORECASE)
    reg1.match(put)
except:
    print('Type the url carefully !!')
    sys.exit()
fol = raw_input('Enter the foldername to save the images : ')
if os.path.isdir(fol):
    thefunc(put, fol)
else:
    subprocess.call('mkdir', fol)
    thefunc(put, fol)

我对 aspx 检测和创建 aspx 页面的标题做了一些修改,但是接下来如何修改我被困在这里

***here is the aspx page link***http://www.foxrun.com.au/Products/Cylinders_with_Gadgets.aspx

抱歉,如果我不清楚,您可以看到我是编程新手,我要问的问题是,当我单击下一页时,如何获取从 aspx 页面获取的图像浏览器中的按钮导致如果我只能抓取一个页面导致 url 不会改变,除非我以某种方式发送 http 帖子告诉页面显示带有新图片的下一页,因为 url 保持不变我希望我清楚

【问题讨论】:

    标签: python html asp.net python-2.7 web-scraping


    【解决方案1】:

    您可以使用请求通过使用可以从初始页面解析的正确数据发布到 url 来实现:

    import requests
    from bs4 import BeautifulSoup
    from urlparse import urljoin
    from itertools import chain
    
    url = "http://www.foxrun.com.au/Products/Cylinders_with_Gadgets.aspx"
    
    
    def validate(soup):
        return {"__VIEWSTATE": soup.select_one("#__VIEWSTATE")["value"],
                "__VIEWSTATEGENERATOR": soup.select_one("#__VIEWSTATEGENERATOR")["value"],
                "__EVENTVALIDATION": soup.select_one("#__EVENTVALIDATION")["value"]}
    
    
    def parse(base, url):
        data = {"__ASYNCPOST": "true"
                }
        h = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17'}
        soup = BeautifulSoup(requests.get(url).text)
        data.update(validate(soup))
        # gets links for < 1,2,3,4,5,6>
        pages = [a["id"] for a in soup.select("a[id^=ctl01_ctl00_pbsc1_pbPagerBottom_btnP]")][2:]
        # get images from initial page
        yield [img["src"] for img in soup.select("img")]
        # add token for post 
        data.update(validate(soup))
        for p in pages:
            # we need $ in place of _ for the form data
            data["__EVENTTARGET"] = p.replace("_", "$")
            data["RadScriptManager1"] = "ctl01$ctl00$pbsc1$ctl01$ctl00$pbsc1$ajaxPanel1Panel|{}".format(p.replace("_", "$"))
            r = requests.post(url, data=data, headers=h).text
            soup = BeautifulSoup(r)
            yield [urljoin(base, img["src"]) for img in soup.select("img")]
    
    
    for url in chain.from_iterable(parse("http://www.foxrun.com.au/", url)):
        print(url)
    

    这将为您提供链接,您只需下载内容并将其写入文件。通常我们可以创建一个 Session 并从一页转到下一页,但在这种情况下,发布的是 ctl01$ctl00$pbsc1$pbPagerBottom$btnNext 从初始页到第二页可以正常工作,但没有概念从第二个到第三个等等。因为我们在表单数据中没有页码。

    【讨论】:

    • 这是我一直在寻找的方法,谢谢
    【解决方案2】:

    我所在的地方的互联网真的很糟糕,所以我不能保证 100% 可以正常工作,但您要执行的操作介于这两行之间。

    这适用于任何类型的页面。如果我解释有任何错误,请不要犹豫发表评论。

    import urllib2
    from urlparse import urljoin
    from urllib import urlretrieve
    from bs4 import BeautifulSoup
    
    url = "http://www.foxrun.com.au/Products/Cylinders_with_Gadgets.aspx"
    html = urllib2.urlopen(url)
    soup = BeautifulSoup(html)
    imgs = soup.findAll("img")
    image=0
    for img in imgs:
        link=urljoin(url,img['src']) #Join relative paths
        urlretrieve(link, "image"+str(image)) #saves image in the folder you execute this
        image+=1 #increments name
    

    这将创建

    image1 image2 ... imageN

    根据需要更改目标路径

    编辑:

    这与aspx无关。

    页面链接是 javascript 生成的,因此您无法从中提取 url。 urrlib 不处理动态生成的内容,因此在这种情况下,您将不得不使用浏览器模拟器,例如 Selenium+Firefox()/PhantomJS 或者您可以使用 Splash。还有CasperJS+ PhantomJS。可能性是无穷无尽的,但我会选择 Selenium :)

    使用这些工具,您可以像在浏览器中一样与页面进行交互(单击、滚动、在框内输入文本等)

    【讨论】:

    • 对不起,如果我不清楚,因为您可以看到我是编程新手,我要问的问题是当我单击下一页按钮时如何获取从 aspx 页面获取的图像在浏览器中,如果我只能抓取一个页面,导致 url 不会改变,除非我以某种方式发送 http 帖子告诉页面显示带有新图片的下一页,因为 url 保持不变,我希望我清楚跨度>
    • @ShantanuBedajna 已更新,祝你好运,如果此答案对您有所帮助,请将其标记为正确 :)
    猜你喜欢
    • 2016-11-27
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多