【问题标题】:not iterating the list in web scraping不在网络抓取中迭代列表
【发布时间】:2017-12-01 19:02:12
【问题描述】:

通过链接,我正在尝试创建两个列表:一个用于国家/地区,另一个用于货币。但是,我被困在某个地方,它只给了我第一个国家名称,但没有迭代到所有国家的列表。任何有关如何解决此问题的帮助将不胜感激。在此先感谢。

这是我的尝试:

from bs4 import BeautifulSoup
import urllib.request

url = "http://www.worldatlas.com/aatlas/infopage/currency.htm"
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 
10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 
Safari/537.36'}

req = urllib.request.Request(url, headers=headers)
resp = urllib.request.urlopen(req)
html = resp.read()

soup = BeautifulSoup(html, "html.parser")
attr = {"class" : "miscTxt"}

countries = soup.find_all("div", attrs=attr)
countries_list = [tr.td.string for tr in countries]

for country in countries_list:
    print(country)

【问题讨论】:

  • 您是否打印出countries_list 来检查它是否包含多个条目?
  • 是的,我做到了。它只打印列表中的第一个国家
  • 我刚刚检查了你的countries_list,它只包含Afghanistan。不是迭代,问题是[tr.td.string for tr in countries]

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

您还可以使用单个理解列表创建一个元组列表,例如 [(country, currency)],然后使用 map & zip 将元组转换为 2 个列表:

temp_list = [
    (t[0].text.strip(), t[1].text.strip()) 
    for t in (t.find_all('td') for t in countries[0].find_all('tr'))
    if t
]

countries_list, currency_list = map(list,zip(*temp_list))

完整代码:

from bs4 import BeautifulSoup
import urllib.request

req = urllib.request.Request("http://www.worldatlas.com/aatlas/infopage/currency.htm")

soup = BeautifulSoup(urllib.request.urlopen(req).read(), "html.parser")

countries = soup.find_all("div", attrs = {"class" : "miscTxt"})

temp_list = [
    (t[0].text.strip(), t[1].text.strip()) 
    for t in (t.find_all('td') for t in countries[0].find_all('tr'))
    if t
]

countries_list, currency_list = map(list,zip(*temp_list))

print(countries_list)
print(currency_list)

【讨论】:

    【解决方案2】:

    试试这个脚本。它应该为您提供国家名称以及相应的货币。您不需要为此网站使用标题。

    from bs4 import BeautifulSoup
    import urllib.request
    
    url = "http://www.worldatlas.com/aatlas/infopage/currency.htm"
    resp = urllib.request.urlopen(urllib.request.Request(url)).read()
    soup = BeautifulSoup(resp, "lxml")
    
    for item in soup.select("table tr"):
        try:
            country = item.select("td")[0].text.strip()
        except IndexError:
            country = ""
        try:
            currency = item.select("td")[0].find_next_sibling().text.strip()
        except IndexError:
            currency = ""
        print(country,currency)
    

    部分输出:

    Afghanistan afghani
    Algeria dinar
    Andorra euro
    Argentina peso
    Australia dollar
    

    【讨论】:

      猜你喜欢
      • 2015-09-05
      • 2023-03-17
      • 1970-01-01
      • 2021-03-10
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多