使用PyQuery获得链接

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

例:from pyquery import PyQuery as pq

         doc = pq(url="https://www.landi.com",encoding='utf-8')

         h = doc('a')

         for i in h:

             f = doc(i).attr('href')

             if f != None and  f != '/' and f != 'javascript:;':

                 s = ''

                 sd = str(doc(i).attr('href')).strip()

                 sds = sd[0:4]

                 if sds != 'http':

                     sd = 'https://www.landi.com'+sd

                 print((str(sd)).strip())

爬取糗事百科文章

例:import urllib.request as rq

         import re

         def gc(u,p):

             #模拟成浏览器

             h = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6788.400 QQBrowser/10.3.2767.400")

             o = rq.build_opener()

             o.addheaders = [h]

             #将opener安装为全局

             rq.install_opener(o)

             d = rq.urlopen(u).read().decode("UTF-8")

             #构建对应用户提取的正则表达式

             e = '<div class="author clearfix">(.*?)</div>'

             #构建段子内容提取的正则表达式

             c = '<div class="content">(.*?)</div>'

             q = '<h2>(.*?)</h2>'

             o = '<span>(.*?)</span>'

             # 寻找出所有的用户

             t = re.compile(e, re.S).findall(d)

             #寻找所有内容             
             l = re.compile(c,re.S).findall(d)

     x=0

             #通过for循环遍历段子内容分别赋给对应的变量

             for n in t:

                 r = re.compile(q, re.S).findall(n)

                 print(r)

                 j = re.compile(o, re.S).findall(l[x])

                 print(j)

                 # exit()

                 x+=1

         #分别获得各页的段子,通过for循环可以获得多页

         for i in range(1,14):

             u = "http://www.qiushibaike.com/text/page/"+str(i)

             gc(u,i) 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄