如何在scrapy框架下,用python实现爬虫自动跳转页面来抓去网页内容

2024-05-06 10:34

1. 如何在scrapy框架下,用python实现爬虫自动跳转页面来抓去网页内容

(1)一种是像我之前爬虫新京报网的新闻,下一页的url可以通过审查元素获得,第一页的网址是http://www.bjnews.com.cn/news/list-43-page-1.html
在第一页的时候,下一页按钮的审查元素是


我们通过获取next_pages = response.xpath('//div[@id="page"]/a[@class="next"]/@href').extract()[0]
,便可以得到下一页的url,next_page = "http://www.bjnews.com.cn" + next_pages,

这一部分的完整代码为:

page_link=set() #保存下一页页面url

content_link=set() #保存页面内所有可获得的url

rules={'page':LinkExtractor(allow=(r'^http://www.bjnews.com.cn/\w+/2016/\d{2}/\d{2}/\d{6}.html
))}

start_urls={'http://www.bjnews.com.cn/news/list-43-page-1.html'}

def parse(self, response):

#爬取一个页面内的所有url链接

    for link in self.rules['page'].extract_links(response):

        if link.url not in self.content_link:

            self.page_link.add(link.url)

            yield scrapy.Request(link.url, callback=self.parse_item)

#自动获取下一页的url

    next_pages = response.xpath('//div[@id="page"]/a[@class="next"]/@href').extract()[0]

    if next_pages:

        next_page = "http://www.bjnews.com.cn" + next_pages

        self.page_link.add(next_page)

        yield scrapy.Request(next_page, callback=self.parse)


(2)第二种情况,就是在下一页的审查元素中没有提供url链接,需要自己分析,在这里依然举个例子,比如搜狐新闻http://news.sohu.com/guojixinwen.shtml,该页中下一页按钮的审查元素是:




我们不能通过href来直接过得下一页的url,需要自己手动获得,那现在我们来分析

第二页的url:http://news.sohu.com/guojixinwen_5230.shtml,第三页的http://news.sohu.com/guojixinwen_5229.shtml,最后一页的http://news.sohu.com/guojixinwen_5132.shtml,由此可以分析出这一共100页的url,是http://news.sohu.com/guoneixinwen_"+i+".shtml",其中i是从5230到5132倒序排列的,也就是说通过for循环,就可以获得这100页的所有url,完整代码如下:在这里给大家加一个新的方法的使用start_request,该方法就是子定义start_urls,把所有自定义的url放到page_link中,self.make_requests_from_url方法会自动获取里面的请求

如何在scrapy框架下,用python实现爬虫自动跳转页面来抓去网页内容

2. 如何用Python爬虫抓取网页内容?

爬虫流程
其实把网络爬虫抽象开来看,它无外乎包含如下几个步骤
模拟请求网页。模拟浏览器,打开目标网站。
获取数据。打开网站之后,就可以自动化的获取我们所需要的网站数据。
保存数据。拿到数据之后,需要持久化到本地文件或者数据库等存储设备中。
那么我们该如何使用 Python 来编写自己的爬虫程序呢,在这里我要重点介绍一个 Python 库:Requests。
Requests 使用
Requests 库是 Python 中发起 HTTP 请求的库,使用非常方便简单。
模拟发送 HTTP 请求
发送 GET 请求
当我们用浏览器打开豆瓣首页时,其实发送的最原始的请求就是 GET 请求
import requests 
res = requests.get('http://www.douban.com') 
print(res) 
print(type(res)) 
>>> 
 

3. 在scrapy框架下用python爬虫的问题!

这个是unicode的,编码成gbk打印就是中文了  encode('gbk')

在scrapy框架下用python爬虫的问题!

4. python 如何抓取动态页面内容?

输入url,得到html,我早就写了函数了
自己搜:
getUrlRespHtml
就可以找到对应的python函数:
#------------------------------------------------------------------------------def getUrlResponse(url, postDict={}, headerDict={}, timeout=0, useGzip=False, postDataDelimiter="&") :    """Get response from url, support optional postDict,headerDict,timeout,useGzip    Note:    1. if postDict not null, url request auto become to POST instead of default GET    2  if you want to auto handle cookies, should call initAutoHandleCookies() before use this function.       then following urllib2.Request will auto handle cookies    """    # makesure url is string, not unicode, otherwise urllib2.urlopen will error    url = str(url);    if (postDict) :        if(postDataDelimiter=="&"):            postData = urllib.urlencode(postDict);        else:            postData = "";            for eachKey in postDict.keys() :                postData += str(eachKey) + "="  + str(postDict[eachKey]) + postDataDelimiter;        postData = postData.strip();        logging.info("postData=%s", postData);        req = urllib2.Request(url, postData);        logging.info("req=%s", req);        req.add_header('Content-Type', "application/x-www-form-urlencoded");    else :        req = urllib2.Request(url);    defHeaderDict = {        'User-Agent'    : gConst['UserAgent'],        'Cache-Control' : 'no-cache',        'Accept'        : '*/*',        'Connection'    : 'Keep-Alive',    };    # add default headers firstly    for eachDefHd in defHeaderDict.keys() :        #print "add default header: %s=%s"%(eachDefHd,defHeaderDict[eachDefHd]);        req.add_header(eachDefHd, defHeaderDict[eachDefHd]);    if(useGzip) :        #print "use gzip for",url;        req.add_header('Accept-Encoding', 'gzip, deflate');    # add customized header later -> allow overwrite default header     if(headerDict) :        #print "added header:",headerDict;        for key in headerDict.keys() :            req.add_header(key, headerDict[key]);    if(timeout > 0) :        # set timeout value if necessary        resp = urllib2.urlopen(req, timeout=timeout);    else :        resp = urllib2.urlopen(req);            #update cookies into local file    if(gVal['cookieUseFile']):        gVal['cj'].save();        logging.info("gVal['cj']=%s", gVal['cj']);        return resp;#------------------------------------------------------------------------------# get response html==body from url#def getUrlRespHtml(url, postDict={}, headerDict={}, timeout=0, useGzip=False) :def getUrlRespHtml(url, postDict={}, headerDict={}, timeout=0, useGzip=True, postDataDelimiter="&") :    resp = getUrlResponse(url, postDict, headerDict, timeout, useGzip, postDataDelimiter);    respHtml = resp.read();        #here, maybe, even if not send Accept-Encoding: gzip, deflate    #but still response gzip or deflate, so directly do undecompress    #if(useGzip) :        #print "---before unzip, len(respHtml)=",len(respHtml);    respInfo = resp.info();        # Server: nginx/1.0.8    # Date: Sun, 08 Apr 2012 12:30:35 GMT    # Content-Type: text/html    # Transfer-Encoding: chunked    # Connection: close    # Vary: Accept-Encoding    # ...    # Content-Encoding: gzip        # sometime, the request use gzip,deflate, but actually returned is un-gzip html    # -> response info not include above "Content-Encoding: gzip"    # eg: http://blog.sina.com.cn/s/comment_730793bf010144j7_3.html    # -> so here only decode when it is indeed is gziped data        #Content-Encoding: deflate    if("Content-Encoding" in respInfo):        if("gzip" == respInfo['Content-Encoding']):            respHtml = zlib.decompress(respHtml, 16+zlib.MAX_WBITS);        elif("deflate" == respInfo['Content-Encoding']):            respHtml = zlib.decompress(respHtml, -zlib.MAX_WBITS);    return respHtml;及示例代码:
url = "http://www.crifan.com";respHtml = getUrlRespHtml(url);
完全库函数,自己搜:
crifanLib.py

关于抓取动态页面,详见:
Python专题教程:抓取网站,模拟登陆,抓取动态网页

(自己搜标题即可找到)

5. 如何用python实现爬虫抓取网页时自动翻页

看了你这个网站,下一页每次都不一样,每一页的链接也不一样,这种你靠分析肯定是不行的,因为你永远都不知道会出来什么内容,建议你用八爪鱼采集器,这是目前最好用的网页数据采集利器,解决这种问题很轻松的。

如何用python实现爬虫抓取网页时自动翻页

6. 如何用python写个爬虫抓去文章

这要看你想爬的文章是哪个网站的,然后通过分析这个网站的文章存储方式以及如何获得所有文章的链接,最后才是用python去实现这个爬取的过程

7. python爬虫如何获取网页的JS动态生成的内容?

对比一下过滤和没有过滤的标签,看看哪些属性不同,根据这些不同的属性来选择。

python爬虫如何获取网页的JS动态生成的内容?

8. 如何用Python爬虫抓取JS动态筛选内容

打开浏览器,以google chrome为例,输入你上面的网址。然后按F12打开调试窗口,然后尝试勾选左边某一个选项,马上可以看到右边的调试窗口有东西输出。找到第一个输出的行,点击header,可以看到每一个都是用的post方法。所以只需要构造相应的header并post上去,就可以得到你想要的数据了。
尝试每一个request都点开看一下
就是你要构造的数据
FormData就是你要构造的数据
把数据构造好然后使用post函数发送给网站

这个得到的是一个网页格式的数据。

而这个发放返回的是json数据,然后编码成dict格式 提取出数据就可以了。
最新文章
热门文章
推荐阅读