Python3导入抓取的URL至CSV时单元格异常问题求助
Hey Garrett, let's work through this CSV wrinkle you're hitting with your scraped URLs! It sounds like you're running into two common pitfalls with how Python's csv module handles iterables—let's break down what's happening and fix it.
What's Causing the Problem?
The csv.writer's writerow() method expects an iterable of values (like a list or tuple), where each item maps to a single CSV cell. Here's why you're seeing those wonky results:
- When you pass the URL string directly (without brackets), Python treats the string itself as an iterable—so it splits every character into its own cell.
- When you wrap
filter_recordsin a single set of brackets (like[filter_records]), you're turning your entire collection of URLs into one big list item. The writer then shoves all those URLs into a single cell.
Fixes for Common Scenarios
Let's cover the most likely use cases with concrete code examples:
1. Writing a Single URL to One Cell
If you have one URL to save, wrap it in a single-element list so writerow() recognizes it as one cell value:
import csv scraped_url = "https://example.com/your-scraped-page" with open("urls.csv", "w", newline="") as csv_file: writer = csv.writer(csv_file) writer.writerow([scraped_url]) # The brackets here are key!
2. Writing Multiple URLs to Separate Cells (Same Row)
If you want all URLs in one row, each in their own cell, pass your list of URLs directly to writerow():
import csv filter_records = ["https://example.com/page1", "https://example.com/page2", "https://example.com/page3"] with open("urls.csv", "w", newline="") as csv_file: writer = csv.writer(csv_file) writer.writerow(filter_records) # No extra brackets—just the list itself
3. Writing Each URL to Its Own Row
If you want one URL per row (most common for scraped data), loop through your URLs and write each as a single-element list:
import csv filter_records = ["https://example.com/page1", "https://example.com/page2", "https://example.com/page3"] with open("urls.csv", "w", newline="") as csv_file: writer = csv.writer(csv_file) for url in filter_records: writer.writerow([url]) # Wrap each individual URL in brackets
Quick Check
Double-check what filter_records actually contains: if it's a single URL string, use scenario 1. If it's a list of URLs, use scenario 2 or 3 depending on your desired layout.
内容的提问来源于stack exchange,提问作者gtjoeckel

