Web 抓取 Yelp,如何检索每个单独评分的值?
Web scraping Yelp, how do I retrieve the value of each individual rating?
从事网络抓取项目以积累我的知识(初学者)。这段代码很乱,但我目前可以打印每条评论的评分。如何从 bs4 对象中提取评分,即列表中的 4.0、5、0,然后取它们的平均值?
Output:
[<meta content="4.0" itemprop="ratingValue"/>, <meta content="5.0" itemprop="ratingValue"/>, ... ]
import mechanize
from bs4 import BeautifulSoup
def searchYelp():
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open('https://www.yelp.com')
br.select_form(nr=0)
br.form['find_desc'] = 'Del Taco'
br.form['find_loc'] = 'New York City'
br.submit()
link_list = []
for link in br.links():
if link.url.startswith('/biz/'):
link_list.append(link.url)
break
big_list_of_ratings = []
yelpPage = br.open(link_list[0])
soup = BeautifulSoup(yelpPage.read(), 'html.parser')
for review in soup.find_all('meta'):
if review.get('itemprop') == 'ratingValue':
big_list_of_ratings.append(review)
print(big_list_of_ratings)
searchYelp()
而不是这个
for review in soup.find_all('meta'):
if review.get('itemprop') == 'ratingValue':
big_list_of_ratings.append(review)
像这样添加属性review['content']
for review in soup.find_all('meta'):
if review.get('itemprop') == 'ratingValue':
big_list_of_ratings.append(review['content'])
或者我建议使用 css 选择器。
for review in soup.select('meta[itemprop="ratingValue"][content]'):
big_list_of_ratings.append(review['content'])
从事网络抓取项目以积累我的知识(初学者)。这段代码很乱,但我目前可以打印每条评论的评分。如何从 bs4 对象中提取评分,即列表中的 4.0、5、0,然后取它们的平均值?
Output:
[<meta content="4.0" itemprop="ratingValue"/>, <meta content="5.0" itemprop="ratingValue"/>, ... ]
import mechanize
from bs4 import BeautifulSoup
def searchYelp():
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
response = br.open('https://www.yelp.com')
br.select_form(nr=0)
br.form['find_desc'] = 'Del Taco'
br.form['find_loc'] = 'New York City'
br.submit()
link_list = []
for link in br.links():
if link.url.startswith('/biz/'):
link_list.append(link.url)
break
big_list_of_ratings = []
yelpPage = br.open(link_list[0])
soup = BeautifulSoup(yelpPage.read(), 'html.parser')
for review in soup.find_all('meta'):
if review.get('itemprop') == 'ratingValue':
big_list_of_ratings.append(review)
print(big_list_of_ratings)
searchYelp()
而不是这个
for review in soup.find_all('meta'):
if review.get('itemprop') == 'ratingValue':
big_list_of_ratings.append(review)
像这样添加属性review['content']
for review in soup.find_all('meta'):
if review.get('itemprop') == 'ratingValue':
big_list_of_ratings.append(review['content'])
或者我建议使用 css 选择器。
for review in soup.select('meta[itemprop="ratingValue"][content]'):
big_list_of_ratings.append(review['content'])