我想在返回的 http header 中找到一个 url。根据beautiful soup有一种方法可以使用 soup.find_all(re.compile("yourRegex") 来收集数组中的正则表达式匹配项。但是,我的正则表达式中一定遗漏了一些东西,它在text editor that I am using 的正则表达式查找,但与以下代码的内部不匹配:
从 bs4 导入 BeautifulSoup 导入请求 重新进口 导入 csv 导入 json 导入时间 导入文件输入 导入 urllib2
data = urllib2.urlopen("http://stackoverflow.com/questions/16627227/http-error-403-in-python-3-web-scraping").read()
soup = BeautifulSoup(data)
stringSoup = str(soup)
#Trying to use compile
print soup.find_all(re.compile("[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"))
我试过将 () 放在正则表达式周围,并以 r 开头……我错过了什么是必要的?
我也一直在使用 http://www.pythonregex.com/ , 把 [a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])? 在正则表达式部分和 url另一部分,但那里也没有匹配项。 谢谢!
请您参考如下方法:
print re.findall(r"[a-zA-Z0-9\-\.]+\.(?:com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)+(?:[\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?",x)
试试这个。这对我有用。
x="""<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/QAPage">
<head>
"""
输出:schema.org/QAPage
