我写了下面一行代码
#!/usr/bin/python
#weather.scrapper
from bs4 import BeautifulSoup
import urllib
def main():
"""weather scrapper"""
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
。你知道吗您的代码已修改(根据您的注释有更多表):
相关问题 更多 >
编程相关推荐