python - Python代码在csv文件中只打印一行
问题描述
最近我尝试编写一个 yp.com 列表抓取工具。但无法弄清楚为什么代码在 .csv 文件中只打印一行。
yp_urls.txt网址是:
https://www.yellowpages.com/search-map?search_terms=restaurant&geo_location_terms= 波士顿 https://www.yellowpages.com/search-map?search_terms=restaurant&geo_location_terms=波士顿& page=2
这是代码:
from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
with open('yp_urls.txt', 'r') as f:
for url in f:
print(url)
uClient = urlopen(url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
containers = page_soup.findAll("div",{"class":"v-card"})
#container= containers[0]
out_filename = "yp_listing.csv"
headers = "URL \n"
f = open(out_filename, "w")
f.write(headers)
for container in containers:
business = container.a["href"].title()
print("business:" + business + "\n" )
f.write(business + "," + "\n")
f.close() # Close the file
解决方案
f.write 命令似乎在您的循环之外,因此只有在循环完成后才会被命中。
例如,代码循环通过 url,然后退出循环并执行 f.write(headers),然后循环通过容器,退出该循环和 f.write(business:..)
您可能还希望使用“w”(写入/覆盖)与“a”(附加)检查输出文件是否以正确的状态打开。也许还可以考虑更改手柄,因此两者都不是“f”。
推荐阅读
- json - 为什么 `minLengh` 不验证 JSON Schema 中缺少的属性?
- java - 如何在 Android Studio 中使用 RecyclerView 显示数据?
- python - 如何清理包含'[]'的nlp文本
- java - Java 方法引用的 TypeScript 等效项
- windows - 在 powershell ssh 会话中访问 Windows 网络驱动器
- python - 如何保存和恢复每个小部件实例唯一的小部件属性?
- callback - 散景 - 根据所选点更改平均值
- django-rest-framework - drf_yasg 文档参数未显示
- javascript - 在 insertAfter() 中使用 $(this).find('class')
- javascript - 一个说用户输入的机器人