BeautifulSoup HTML 使用正则表达式解析
BeautifulSoup HTML Parsing using regex
我正在尝试解析 IMDB.com 中的四个 HTML 页。我想从每个列表中提取所有 IMDB ID(这可以在 HTML 代码中找到,看起来像这样:href="/title/tt0080684/" title="Star Wars: Episode V - The Empire Strikes Back (1980)"但是我似乎无法让下面的正则表达式工作...正则表达式或 beautifulsoup 的语法有问题吗?谢谢!
import urllib2
from bs4 import BeautifulSoup
import re, json
for start_num in ('1', '2', '3', '4'):
response = urllib2.urlopen('http://www.imdb.com/search/title?at=0&genres=sci_fi&sort=user_rating&start='+ start_num +'&title_type=feature')
html_doc = response.read()
soup = BeautifulSoup(html_doc, "html.parser")
for movie in soup.find_all(re.compile('\"href=\"/title/\"')):
print(tag.name)
您将 find_all()
与正则表达式一起使用不正确。如果您希望 BeautifulSoup
根据正则表达式检查 href
属性值,您需要提供一个带有正则表达式作为值的 href
关键字参数:
for movie in soup.find_all(href=re.compile(r'/title/')):
print(tag.name)
我猜你想获取标签及其内容,也就是电影 name.The 正则表达式错误(href 左边没有引号)。你可以试试这个:
re.compile('href=\"/title/\"')
希望能成功
我正在尝试解析 IMDB.com 中的四个 HTML 页。我想从每个列表中提取所有 IMDB ID(这可以在 HTML 代码中找到,看起来像这样:href="/title/tt0080684/" title="Star Wars: Episode V - The Empire Strikes Back (1980)"但是我似乎无法让下面的正则表达式工作...正则表达式或 beautifulsoup 的语法有问题吗?谢谢!
import urllib2
from bs4 import BeautifulSoup
import re, json
for start_num in ('1', '2', '3', '4'):
response = urllib2.urlopen('http://www.imdb.com/search/title?at=0&genres=sci_fi&sort=user_rating&start='+ start_num +'&title_type=feature')
html_doc = response.read()
soup = BeautifulSoup(html_doc, "html.parser")
for movie in soup.find_all(re.compile('\"href=\"/title/\"')):
print(tag.name)
您将 find_all()
与正则表达式一起使用不正确。如果您希望 BeautifulSoup
根据正则表达式检查 href
属性值,您需要提供一个带有正则表达式作为值的 href
关键字参数:
for movie in soup.find_all(href=re.compile(r'/title/')):
print(tag.name)
我猜你想获取标签及其内容,也就是电影 name.The 正则表达式错误(href 左边没有引号)。你可以试试这个:
re.compile('href=\"/title/\"')
希望能成功