内容简介:翻译自:https://stackoverflow.com/questions/20045955/regex-pattern-in-python-for-parsing-html-title-tags
中使用re模块和urllib模块,并尝试编写一个简单的Web scraper.这是我写的代码,只是为了抓住网站的标题:
#!/usr/bin/python
import urllib
import re
urls=["http://google.com","https://facebook.com","http://reddit.com"]
i=0
these_regex="<title>(.+?)</title>"
pattern=re.compile(these_regex)
while(i<len(urls)):
htmlfile=urllib.urlopen(urls[i])
htmltext=htmlfile.read()
titles=re.findall(pattern,htmltext)
print titles
i+=1
这为Google和Reddit提供了正确的输出,但没有为Facebook提供 – 就像这样:
['Google'] [] ['reddit: the front page of the internet']
这是因为,我在Facebook页面上发现标题标签如下:<title id =“pageTitle”>.为了适应额外的id =,我修改了these_regex变量,如下所示:these_regex =“<title.?>(.?)</ title>”.但是这给出了以下输出:
[] ['Welcome to Facebook \xe2\x80\x94 Log in, sign up or learn more'] []
我如何将两者结合起来,以便我可以考虑标题标签中传递的任何其他参数?
您正在使用正则表达式,并且将HTML与此类表达式匹配变得太复杂,太快.
使用HTML解析器,Python有几个可供选择.我建议您使用 BeautifulSoup ,一个受欢迎的第三方库.
BeautifulSoup示例:
from bs4 import BeautifulSoup
response = urllib2.urlopen(url)
soup = BeautifulSoup(response.read(), from_encoding=response.info().getparam('charset'))
title = soup.find('title').text
由于标题标签本身不包含其他标签,因此您可以在此处使用正则表达式,但只要您尝试解析嵌套标签,就会遇到非常复杂的问题.
您可以通过匹配标题标记中的其他字符来解决您的具体问题:
r'<title[^>]*>([^<]+)</title>'
这匹配0个或更多不是结束的字符>托架.这里的’0或更多’可以让你匹配额外的属性和普通的<title>标签.
翻译自:https://stackoverflow.com/questions/20045955/regex-pattern-in-python-for-parsing-html-title-tags
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Code Reading
Diomidis Spinellis / Addison-Wesley Professional / 2003-06-06 / USD 64.99
This book is a unique and essential reference that focuses upon the reading and comprehension of existing software code. While code reading is an important task faced by the vast majority of students,......一起来看看 《Code Reading》 这本书的介绍吧!