BeautifulSoup SoupStrainer应变html和pdf链接

2024-10-01 17:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要传递什么作为regex模式从html网页获取html和pdf?到目前为止,我所掌握的情况如下。我以为我需要使用OR语句,但这并没有如预期的那样起作用。在

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']

Tags: orhttp网页pdfresponserequesthtmlstatus
1条回答
网友
1楼 · 发布于 2024-10-01 17:34:35
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

相关问题 更多 >

    热门问题