【问题标题】:How to loop through a list number reference如何遍历列表编号参考
【发布时间】:2017-10-02 03:08:08
【问题描述】:

我正在尝试对 yelp 评论进行分析,但在循环浏览多个评论时遇到了问题。我当前的代码:

import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.yelp.com/biz/pizzafire-cleveland')
soup = BeautifulSoup(r.text, 'html.parser')
results = soup.find_all('div', class_='review review--with-sidebar')

records=[]
for result in results:
    a = 0
    while a<21:
        a += 1
    first_result = results[len(a)]   #this is where my code is breaking

#get review
    REV1 = first_result.find('p').text
    print REV1


#get date
    Date = first_result.find('span', class_='rating-qualifier').text
    print Date

#get username
    username = first_result.find('li', class_='user-name').text

#get user location
    userlocation = first_result.find('b').text

#get userrating
    userrating = first_result.find('img', class_='offscreen').get('alt')

#get userstats
    userstats = first_result.find('ul', class_='user-passport-
    stats').text.split()

    friendcount = userstats[0]
    reviewcount = userstats[2]
    photouploadcount = userstats[4]
    yelpstatus = userstats[6]

#get user link
    links=[]
    for a in results[0]('a', href=True):
        links.append(a['href'].split())

    userlink= str(links[0])[4:-2]
    print userlink    

results[0] 指的是第一次审查。我希望它继续审查 1, 2等。有谁知道如何循环遍历first_result中的结果?

谢谢你, 纳扎尔

【问题讨论】:

  • results 是什么类型?的列表 ...?你想用 for 循环的开头来完成什么?
  • results[len(a)] 应该导致TypeError,因为int 类型的对象没有len()。你的意思是results[a]?另请注意,while a&lt;21: a += 1 似乎没有任何意义。你可以只使用单行first_result = results[21]

标签: python python-2.7 web-scraping beautifulsoup python-requests


【解决方案1】:

应该还是results(a),而不是results(len(a)):

a = 0
while a < 21:
    a += 1
    first_result = results[a]

此外,使用 for 循环可以更好地执行此操作:

for a in range(21):
    first_result = results[a]

但是,这只会将 first_result 重置为结果中的所有内容。这里似乎有很多格式问题需要解决。

【讨论】:

    【解决方案2】:

    for 循环的前几行是多余的。正如 Evan Nowak 所建议的,

    for a in range(21):
        first_result = results[a]
    

    会是一个不错的选择。但是由于results是一个列表,你可以进一步缩短它:

    for result in result:
    

    在您的原始代码中,除了将其分配给first_result 之外,您没有在任何地方使用result 变量。您可以完全消除其中一个,并可能在代码中的任何地方将“first_result”更改为“result”。

    此外,您在内部 for 循环中硬编码值 0:

    for a in results[0]('a', href=True):
        links.append(a['href'].split())
    

    我不认为这是故意的。因此,如果忽略了这一点,请更改它。

    最后,查看The Best of the Best Practices (BOBP) Guide for Python 以获取有关更好的格式和一般编码实践的更多提示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-06
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多