使用BeautifulSoup爬取药智标准网的数据

#coding:utf-8
import urllib2
import bs4
from bs4 import BeautifulSoup
class YZBZ():
    #初始化方法
    def __init__(self):
        self.pageIndex = 1
        self.user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'
        self.headers = { 'User-Agent' : self.user_agent }
    #获取页面代码
    def getHtml(self,pageIndex):
        #异常处理,如果网页连接失败,输出相应内容
        try:
            url='http://db.yaozh.com/biaozhun?p='+ str(pageIndex)
            #构建请求的request
            request=urllib2.Request(url,headers=self.headers)
            page=urllib2.urlopen(request)
            html=page.read()
            return html
        except urllib2.URLError,e:
            if hasattr(e,"reason"):
                print u"连接失败",e.reason
                return None
    #匹配相关内容并写入文件
    #主要思路:通过分析源代码,用BS匹配所有tr,然后写入第一页的标题和内容,其他页则只写入内容无标题
    def getItems(self):
        #一共11页,依次进行遍历
        L=range(1,11)
        for pageIndex in L:
            html=self.getHtml(pageIndex)
            soup=BeautifulSoup(html)
            tr_list=soup.find_all("tr")
            #第一页标题和内容
            if pageIndex==1:
                L1=range(0,21)
                for item1 in L1:
                    with open(r"D:\Python test\yaozhi_biaozhun.txt",'a+') as a:
                        a.write(tr_list[item1].get_text("|",strip=True).encode("utf-8")+"|"+"\n")
            #其他页的内容
            else:
                L2=range(1,21)
                for item2 in L2:
                    a=open(r"D:\Python test\yaozhi_biaozhun.txt","a+")
                    a.write(tr_list[item2].get_text("|",strip=True).encode("utf-8")+"|"+"\n")
                    a.close()


spider=YZBZ()
spider.getItems()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值