【发布时间】:2019-05-28 05:50:54
【问题描述】:
我对 Python 还是很陌生,我的 For 循环很难提取某个站点上的所有 Web 链接。这是我的代码:
import requests
import csv
from bs4 import BeautifulSoup
j= [["Population and Housing Unit Estimates"]] # Title
k= [["Web Links"]] # Column Headings
example_listing='https://www.census.gov/programs-surveys/popest.html' #Source
r=requests.get(example_listing) #Grab page source html
html_page=r.text
soup=BeautifulSoup(html_page,'html.parser') #Build Beautiful Soup object to help parse the html
with open('HTMLList.csv','w',newline="") as f: #Choose what you want to grab
writer=csv.writer(f,delimiter=' ',lineterminator='\r')
writer.writerows(j)
writer.writerows(k)
for link in soup.find_all('a'):
f.append(link.get('href'))
if not f:
""
else:
writer.writerow(f)
f.close()
非常感谢任何帮助。我真的不知道从这里去哪里。谢谢!
【问题讨论】:
-
f不是一个列表...你为什么要附加到它上面? -
你能解释一下你想要的输出是什么以及你尝试了什么吗?也尝试使它稍微更小(查看如何制作minimal reproducible example)
-
旁注:如果您打开带有
with语句的文件,则不需要.close()。with自动执行。
标签: python csv for-loop beautifulsoup