使用BeautifulSoup的SoupStrainer筛选HTML和PDF链接
我需要什么样的正则表达式模式才能从一个网页中提取出HTML文件和PDF文件呢?到目前为止,我有下面这个。我以为我需要用“或”这个语句,但结果并没有像我预期的那样工作。
status, response = http.request("http://www.example.com")
htmlandpdfonly=SoupStrainer('a', href=re.compile('html|pdf'))
for link in BeautifulSoup(response, parseOnlyThese = htmlandpdfonly):
if(link.has_key('href')):
print link['href']
1 个回答
3
import re
from BeautifulSoup import BeautifulSoup
# find ".html" or ".pdf" in a string
match = re.compile('\.(html|pdf)')
# parse page content
status, response = http.request("http://www.example.com")
page = BeautifulSoup(response)
# check links
for link in page.findAll('a'):
try:
href = link['href']
if re.search(match, href):
print href
except KeyError:
pass
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。