在Python中重新排列解析的HTML数据
我几乎没有编程经验,请原谅我的无知 我正试图解析雅虎的“关键统计数据”页面!财务,待具体页面。我一直在和BeautifulSoup鬼混,能够提取出我想要的数据,但后来遇到了精神障碍。我希望数据如下所示:在Python中重新排列解析的HTML数据,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,我几乎没有编程经验,请原谅我的无知 我正试图解析雅虎的“关键统计数据”页面!财务,待具体页面。我一直在和BeautifulSoup鬼混,能够提取出我想要的数据,但后来遇到了精神障碍。我希望数据如下所示: measure[i]: value[i] . . measure[n]: value[n] 但我的脚本得到的结果是: measure[i] . . measure[n] value[i] . . value[n] 下面是我尝试将两个数据字段合并在一起时抛出的错误: mea
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
而且
这将在循环的每次迭代中覆盖x
,因此最后x
只包含最后分配的值,而不包含所有值的总和。在这里,您可能希望像这样使用+
操作符:
for incident in measure:
x += incident.contents # x += y is the same as x = x + y
当然,另一个循环也是如此
measures = ['1', '2', '3', '4']
values = ['a', 'b', 'c', 'd']
for pair in zip(measures, values):
print ': '.join(pair)
# 1: a
# 2: b
# 3: c
# 4: d
关于zip
:
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:<built-in function zip>
Namespace: Python builtin
Docstring:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.
类型:内置函数或方法
基类:
字符串形式:
名称空间:Python内置
文档字符串:
邮政编码(seq1[,seq2[…])->[(seq1[0],seq2[0]…),(…)]
返回元组列表,其中每个元组包含第i个元素
从每个参数序列。返回的列表被截断
长度为最短参数序列的长度。
谢谢您的帮助。您的方法实际上消除了我进入并删除不需要的标记的需要,但正如您所提到的,只显示最后一个值。您建议用什么(有效的)方法来替换我实现的“for”循环以显示所有值的集合?请忽略该注释!我消除了for循环并实现了您的建议。现在剩下要做的就是加入BeautifulSoup并清理不需要的标签。
Type: builtin_function_or_method
Base Class: <type 'builtin_function_or_method'>
String Form:<built-in function zip>
Namespace: Python builtin
Docstring:
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.