开发者社区> 问答> 正文

抓取网站文章代码

# --*--  coding:utf-8 --*--
import urllib2
from bs4 import BeautifulSoup


def getUrlList(url):
    html=urllib2.urlopen(url)
    html=html. read()
     return html



url= 'http://www.pythontab.com/html/pythonhexinbiancheng/index.html'
url_list=[url]
for i in range( 2, 22):
    url_list.append( 'http://www.pythontab.com/html/pythonhexinbiancheng/%s.html' %i)
for j in url_list:
    html=getUrlList(j)
    soup=BeautifulSoup(html, 'html.parser')
    title_list=soup.select( '#catlist > li > a')
     for title in title_list:
        tname = title.get_text().replace( '*', '').replace( '/', '').replace( ',', '')   #获取标题名称
        links = title.get( 'href') #获取内容url
        title_p=getUrlList(links)
        soup1=BeautifulSoup(title_p, 'html.parser')
        jc=soup1.select( 'div.content > p ')
        text=[]
         for k in jc:
             text.append(k.get_text().encode( 'utf-8'))
         print text
         with open( 'pythontab/%s.txt' %tname, 'wb+') as f:
             for a in text:
                f.write(a)

展开
收起
xuyuan.xy 2017-07-29 01:08:43 2975 0
1 条回答
写回答
取消 提交回答
  • 优秀文章-欢迎进行技术分享,感谢你的支持!
    2017-07-30 06:32:59
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
SEO学习步骤 立即下载
基于浏览器的实时构建探索之路 立即下载
Python第五讲——关于爬虫如何做js逆向的思路 立即下载