我正在使用Python 3.3和以下网站: http://www.nasdaq.com/markets/ipos/
我的目标是只阅读即将上市的公司。它在带有div^{cl1}的div标记中$
这是我的密码
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen("http://www.nasdaq.com/markets/ipos/").read()
soup = BeautifulSoup(html)
for divparent in soup.find_all('div', attrs={'class':'genTable thin floatL'}) [0]: # I tried putting a [0] so it will only return divs in the first genTable thin floatL class
for div in soup.find_all('div', attrs={'class':'ipo-cell-height'}):
s = div.string
if re.match(r'\d{1,2}/\d{1,2}/\d{4}$', s):
div_next = div.find_next('div')
print('{} - {}'.format(s, div_next.string))
我只想退货
^{pr2}$但它打印所有div类重新匹配规格和多次。我尝试在for divparent循环中插入[0]以仅检索第一个循环,但这会导致重复问题。在
编辑:这是根据warunsl解决方案更新的代码。这很管用。在
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
html = urlopen("http://www.nasdaq.com/markets/ipos/").read()
soup = BeautifulSoup(html)
divparent = soup.find_all('div', attrs={'class':'genTable thin floatL'})[0]
table= divparent.find('table')
for div in table.find_all('div', attrs={'class':'ipo-cell-height'}):
s = div.string
if re.match(r'\d{1,2}/\d{1,2}/\d{4}$', s):
div_next = div.find_next('div')
print('{} - {}'.format(s, div_next.string))
您提到有两个元素符合
'class':'genTable thin floatL'
标准。因此,为第一个元素运行for循环没有意义。在所以用
现在您不必再做
^{pr2}$soup.find_all
。这样做将搜索整个文档。您需要将搜索限制为divparent
。所以,你要:提取日期和公司名称的代码的其余部分将是相同的,只是它们将引用
table
变量。在希望有帮助。在
相关问题 更多 >
编程相关推荐