我目前正在学习网页抓取和 Python。我想编写一个代码,根据我创建的链接列表下载 .xls 数据文件列表。这些链接中的每一个都下载与一个国家的 FDI 流量相对应的数据文件。
我的问题是,按照当前编写代码的方式,我列表中的最后一个 url 替换了所有以前的文件。这些文件命名正确,但它们都包含列表中最后一个国家/地区的数据。举个例子,我只取数据中的最后三个国家。
from bs4 import BeautifulSoup
import pandas as pd
import requests
import os
page = requests.get("https://unctad.org/en/Pages/DIAE/FDI%20Statistics/FDI-Statistics-Bilateral.aspx")
soup = BeautifulSoup(page.text, 'html.parser')
countries_list = soup.select('[id=FDIcountriesxls] option[value]')
links = [link.get('value') for link in countries_list[203:-1]] #sample of countries
countries = [country.text for country in countries_list[203:-1]] #sample of countries
links_complete = ["https://unctad.org" + link for link in links]
for link in links_complete:
for country in countries:
r=requests.get(link)
with open (country + '.xls', 'wb') as file:
file.write(r.content)
这让我得到三个文件,都以三个国家命名,但包含最后一个(赞比亚)的数据。
有人能帮忙吗?
谢谢。
那是因为您不必进行双循环。实际上,在“countries”循环中,您每次都在文件('wb')上重写,因此只剩下最后一个国家/地区的值。要解决您的问题,您可以直接在 countries_list 上循环
from bs4 import BeautifulSoup
import pandas as pd
import requests
import os
page = requests.get("https://unctad.org/en/Pages/DIAE/FDI%20Statistics/FDI-Statistics-Bilateral.aspx")
soup = BeautifulSoup(page.text, 'html.parser')
countries_list = soup.select('[id=FDIcountriesxls] option[value]')
for opt in countries_list:
value = opt.get('value')
if value:
link = "https://unctad.org" + value
country = opt.get_text()
r = requests.get(link)
with open(country + '.xls', 'wb') as file:
file.write(r.content)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句