爬取每则知乎日报

#Python 3.5
#By A_lPha
#http://blog.csdn.net/a_lpha

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import re

URL = "http://daily.zhihu.com/"

def get_url(URL):
    bsobj = urlopen(URL)
    text = bsobj.read().decode("utf-8")
    return text

def get_reg(bsobj):
    html = str(bsobj)
    reg_url = re.compile(r'<a href="/story/(.*?)" class="link-button">')
    items = re.findall(reg_url, html)
    urls = []
    for item in items:
        urls.append("http://daily.zhihu.com/story/" + item)
    return urls

def get_contect(url):
    html = get_url(url)
    pattern = re.compile('<h1 class="headline-title">(.*?)</h1>')
    items = re.findall(pattern, html)
    print("**" + items[0] + "**")
    pass#需要写正则表达式获取正文内容


html = get_url(URL)
urls = get_reg(html)
for url in urls:
    try:
        get_contect(url)
    except:
        print("出错了")
        break

这是一个爬取知乎日报文章的脚本,算是半成品吧,因为这个脚本的最终目的是通过首页的URL获取每篇文章的URL然后在解析标题和正文内容,没错,还是得用到正则表达式。现在的功力用正则判断标题没问题,但是用来提取正文内容还是差点。不过这段代码的思路很重要。就是通过URL进入另一个URL并找出相关信息,当时这个问题还是困扰我一段时间的。现在解决了。

发布了72 篇原创文章 · 获赞 42 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/A_lPha/article/details/54577099