我写了下面一行代码
#!/usr/bin/python
#weather.scraper
from bs4 import BeautifulSoup
import urllib
def main():
"""weather scraper"""
r = urllib.urlopen("https://www.wunderground.com/history/airport/KPHL/2016/1/1/MonthlyHistory.html?&reqdb.zip=&reqdb.magic=&reqdb.wmo=&MR=1").read()
soup = BeautifulSoup(r, "html.parser")
table = soup.find_all("table", class_="responsive airport-history-summary-table")
tr = soup.find_all("tr")
td = soup.find_all("td")
print table
if __name__ == "__main__":
main()
当我打印表格时,我也会得到所有的html(td、tr、span等)。如何在没有html的情况下打印表(tr、td)的内容?
谢谢
当您想要获取内容时,必须使用
.getText()
方法。由于find_all
返回元素列表,因此必须选择其中一个(td[0]
)或者您可以执行以下操作,例如:
上面的循环为单元格旁边的每行单元格打印
请注意,您确实找到了所有
td
和所有tr
的方法,但您可能只想在table
中找到它们如果要查找
table
中的元素,必须执行以下操作:table.find('tr')
而不是soup.find('tr)
,因此BeautifulSoup
将在table
中寻找tr
而不是整个html
您的代码已修改(根据您关于有更多表的评论):
相关问题 更多 >
编程相关推荐