【发布时间】:2021-02-17 14:16:55
【问题描述】:
我目前有一个程序可以从网站上抓取数据并将其打印出来供用户使用。但是,它也会打印出我不想要的部分抓取数据。这不是所有的代码,对于我实际需要做的小事来说,这是一个不合情理的数量,但这些是需要的行。
#https://tradingeconomics.com/united-kingdom/indicators
import requests
import urllib.request
import time
import re
from bs4 import BeautifulSoup
web_add = 'https://tradingeconomics.com/united-kingdom/indicators'
web_data = requests.get(web_add)
bs = BeautifulSoup(web_data.text, "html.parser")
up_GDPgrowthRate = str(bs.findAll("td")[21])
varNameBlacklist = "¬`1234567890!\"£$%^&*()_-+=/{[]}:;@'~#|\\<>,.?"
up_GDPgrowthRate = up_GDPgrowthRate.translate({ord(i): None for i in varNameBlacklist})
print(up_GDPgrowthRate)
这是输出:
td stylepaddingleft px textalign left fontweight whitespace normal
a hrefunitedkingdomgdpgrowth
GDP Growth Rate
span classtableunit smallspan
atd
我需要的唯一部分是“GDP 增长率”。我已经尝试了我在网上找到的大多数解决方案。将字符串中的其他字符列入黑名单不起作用,因为这会删除我需要的部分中的一些字符。我尝试使用以下方法打印特定字符位置:
print(up_GDPgrowthRate[158]
print(up_GDPgrowthRate[159]
print(up_GDPgrowthRate[160]
etc
但这会将字符打印在不同的行上。拆分也有同样的问题,因为我不能在一行上打印出来并将单词分配给一个变量。如何将“GDP 增长率”作为单个字符串获取,不包含我不需要的字符?
【问题讨论】:
-
试试
up_GDPgrowthRate = bs.findAll("td")[21].text
标签: python string split character