通过Python正则表达式抓取网页

2 投票
1 回答
1692 浏览
提问于 2025-04-18 20:22

抱歉,我刚接触HTML,请理解我的问题可能很简单。

我想用Python建立一个简单的搜索引擎。

为此,我首先需要建立一个爬虫来获取链接的URL。

我想用正则表达式来提取这些链接的URL。

所以我学习了一下,但我不知道HTML中链接的确切模式是什么。

from urllib import urlopen
import re

webPage = urlopen('http://web.cs.dartmouth.edu/').read()
linkedPage = re.findall(r'what should be filled in here?', webPage)

相关问题:

1 个回答

4

有一些专门用来解析HTML的工具,这些工具叫做 HTML解析器

比如,使用 BeautifulSoup

from urllib2 import urlopen
from bs4 import BeautifulSoup

soup = BeautifulSoup(urlopen('http://web.cs.dartmouth.edu/'))
for article in soup.select('div.view-content article'):
    print article.text

这个代码可以打印出页面上的所有文章:

Prof Sean Smith receives best paper of 2014 award
...
Lorenzo Torresani wins the Google Faculty Research Award
...

另外,建议避免使用正则表达式来解析HTML,原因可以参考以下链接:

撰写回答