使用Python从网站提取文本数据:

时间:2015-12-07 07:43:30

标签: python regex

我正在尝试使用正则表达式从网站提取文本数据,但问题是它没有完全解压缩。我正在学习本教程:https://pythonprogramming.net/parse-website-using-regular-expressions-urllib 但我不知道我错在哪里。我从中提取文本的网站是http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/及其相关的子链接。

代码:

import urllib2
from urllib2 import Request
import re
#url = "http://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm"
url = "http://www.sanfoundry.com/c-programming-questions-answers-variable-names-1/"

req = Request(url)
resp = urllib2.urlopen(req)
respData = resp.read()

regex = '<p.*?>(.*?)<\/p>'

paragraphs = re.findall(regex,str(respData))


for eachP in paragraphs:
    print(eachP)

任何想法???

1 个答案:

答案 0 :(得分:0)

您应该使用BeautifulSoup。这比正则表达式更简单,更好。

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

soup = BeautifulSoup(htmls, 'html.parser')
for p in soup.find_all('p'):
    print p.get_text().encode('utf-8') + "\n\n"

使用utf-8,因为源网址上有unicode文本。

在这里,您将找到如何安装BeautifulSoup

相关问题