python - 在 Python 中重新排列解析的 HTML 数据

标签 python web-scraping beautifulsoup

我的编程经验很少,所以请原谅我的无知。

我正在尝试解析 Yahoo! 的“关键统计数据”页面。具体来说,金融this页。我一直在使用 BeautifulSoup 并能够提取我想要的数据,但此后遇到了心理障碍。我希望数据显示如下:

measure[i]: value[i]
.
.  
measure[n]: value[n]

但是我用脚本得到的结果是:

measure[i]  
.
.    
measure[n]  
value[i]
.
.
value[n]

这是我将两个数据字段连接在一起的尝试,这会引发错误:

measure = soup.findAll('td', {'class':'yfnc_tablehead1'}, width='74%')  
value = soup.findAll('td', {'class':'yfnc_tabledata1'}) 

for incident in measure:
    x = incident.contents

for incident2 in value:
    y = incident2.contents

data = x + y

print ': '.join(data)

此外,我想删除这些值中不需要的字符,但我会阅读 re.compile 和 re.sub 文档。

感谢您的任何意见。

最佳答案

data = x + y

+ 运算符附加列表,如果您想耦合列表中的相应项目,请尝试使用 zip() 函数:

data = zip(x,y)
for m,v in data:
  print m,v

还有,

for incident in measure:
  x = incident.contents

这会在循环的每次迭代中覆盖x,因此最终x仅包含分配的最后一个值,而不是所有值的聚合。在这里,您可能确实想使用 + 运算符,如下所示:

for incident in measure:
  x += incident.contents # x += y is the same as x = x + y

当然,另一个循环也是如此。

关于python - 在 Python 中重新排列解析的 HTML 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9285922/

相关文章:

python - 如何在 Windows 上安装 OpenCV 并在不使用包管理器的情况下为 PyCharm 启用它

python - conda-env 创建失败,并显示一般错误消息 "An unexpected error has occurred."

python - FileNotFoundError : [WinError 2] | Errors reading text from image with Python, OpenCV 和 OCR

javascript - Scrapy splash 响应不会返回完整的 html

python - 使用 selenium 抓取 Instagram 粉丝

python - Django 和 BeautifulSoup - 在每个页面加载时运行views.py?

python - find_all 带有 BeautifulSoup 4 的 camelCase 标签名称

python - numpy数组的可变大小

html - 抓取整个网站

excel - Selenium Webdriver (VBA) - 查找元素的属性,其中有相同名称的重复属性