在网页中搜索

3 投票
2 回答
43043 浏览
提问于 2025-04-16 11:24

嘿,我正在做一个Python项目,需要查看一个网页。我想在网页上找特定的文字,如果找到了,就打印出一些内容。如果没找到,就打印出一个错误信息。我已经尝试过用不同的模块,比如libxml,但我还是不知道该怎么做。

有没有人能帮帮我?

2 个回答

3

lxml真是太棒了:http://lxml.de/parsing.html

我经常用它配合xpath从html中提取数据。

另外一个选择是http://www.crummy.com/software/BeautifulSoup/,这个也很好用。

4

你可以做一些简单的事情,比如:


import urllib2
import re

html_content = urllib2.urlopen('http://www.domain.com').read()

matches = re.findall('regex of string to find', html_content);

if len(matches) == 0: 
   print 'I did not find anything'
else:
   print 'My string is in the html'

撰写回答