import requests
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import re
def text_save(filename, data):
file = open(filename, 'w', encoding = 'utf-8')
for i in range(len(data)):
s = str(data[i]).replace('[', '').replace(']', '')
s = str(data[i]).replace('(', '').replace(')', '')
s = s.replace("'", '').replace(',', '') + '\n'
file.write(s)
file.close()
print("保存文件成功")
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}
url = "http://www.fortunechina.com/fortune500/c/2020-08/10/content_372148.htm"
ret = Request(url,headers=headers)
html = urlopen(ret)
bs = BeautifulSoup(html,"html.parser")
tr = bs.find('tbody').find_all('tr')
listall=[]
for j in tr[0:]:
td = j.find_all('td')
rank = td[0].get_text().strip()
corporate_name = td[1].get_text().strip()
marketing_revenue = td[2].get_text().strip()
profit = td[3].get_text().strip()
country = td[4].get_text().strip()
list = "{0:<10}\t{1:<20}\t{2:<20}\t{3:<20}\t{4:<20}".format(rank, marketing_revenue, profit, country, corporate_name, chr(12288))
listall.append(list)
list = []
text_save('Wealth Rankings.txt', listall)