#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
并找出相关信息,当时这个问题还是困扰我一段时间的。现在解决了。