[英]I need to save scraped urls to a csv file in URI format. file won't write to csv
我是一個認真的新手。 我有一個項目並且遇到了麻煩。 我要創建一個程序來:
1.) 從網站上抓取網絡鏈接,2.) 刪除重復項,3.) 確保所有網絡鏈接都是 URI 格式,以及 4.) 寫入 csv。
我在第 3 步附近遇到了麻煩。我在下面分享的第一段代碼是我無數次失敗的嘗試之一。 問題似乎在於我無法將我的集合轉換回列表並且該集合不可變,或者......我認為我在 Jupyter 中所做的一些事情導致它失去與程序的連接,它無法識別我引用我抓取的鏈接的方式。 請告訴我我在哪里搞砸了。
失敗的嘗試:
save link as BeautifulSoup object
soup= BeautifulSoup
r= urllib.request.urlopen('https://www.census.gov/programs-surveys/popest.html').read()
soup = BeautifulSoup(r,"html.parser")
links=set([a['href'] for a in soup.find_all('a',href=True)])
print(set)
print(links)
f=open('JessicasExport.csv','w', newline='')
writer=csv.writer(f,delimiter=',', lineterminator= '\r')
set=MyList
MyList=[set]
ctr=0
for x in MyList:
MyList.update([x])
if not MyList:
''
elif hrefs.startswith(['#']):
MyList.add(hrefs[1:])
elif hrefs.startswith(['/']):
MyList.add (['https://www.census.gov'+ hrefs])
elif hrefs.endswith(['.gov']):
MyList.add ([hrefs + '/'])
else:
MyList.add([hrefs])
writer.writerow([MyList])
del MyList[:]
ctr += 1
print('Number of urls written to CSV:' , ctr)
f.close()
出[]:#結果錯誤
AttributeError Traceback (most recent call last)
<ipython-input-5-35e0479f6c2e> in <module>
5 ctr=0
6 for x in MyList:
----> 7 MyList.update([x]) 8 如果不是 MyList: 9 ''
AttributeError: 'list' object has no attribute 'update'
然后我調整了它並嘗試了這個。 下面的這段代碼成功地吐出我抓取的鏈接,但沒有向 csv 寫入任何內容,也沒有更正不在 URI 中的代碼部分。 但是.....它沒有產生錯誤代碼,所以我很困惑......非常感謝任何幫助! 幾天來我一直在等待老師的回復,並且急於取得進展。
部分成功的嘗試,沒有錯誤,但不是文件,也沒有附加到 uri
import csv
import requests
from bs4 import BeautifulSoup
import urllib.request
import os
soup= BeautifulSoup
r= urllib.request.urlopen('https://www.census.gov/programs-surveys/popest.html').read()
soup = BeautifulSoup(r,"html.parser")
links=set([a['href'] for a in soup.find_all('a',href=True)])
print(set)
print(links)
f=open('check.csv', 'w', newline='')
writer = csv.writer(f, delimiter=',', lineterminator='\r')
Myset = set()
MyList= [Myset]
ctr=0
for x in Myset:
MyList.append ([x])
if not MyList:
''
elif hrefs.startswith(['#']):
MyList.add(hrefs[1:])
elif hrefs.startswith(['/']):
MyList.add (['https://www.census.gov'+ hrefs])
elif hrefs.endswith(['.gov']):
MyList.add ([hrefs + '/'])
else:
MyList.add([hrefs])
writer.writerow([MyList])
del MyList[:]
ctr += 1
f.close()
感謝所有評論和提出建議的人! 我真的很想明白。
@Mercury是對的,您定義了一個集合(使用大寫 M,您不應該這樣做,因為您應該遵循PEP-8的約定)然后將其放入一個空列表中(也使用大寫 M):您是什么試圖實現? 另外,當您在第一個 if 下方寫入空字符串時,我想您想了解pass
statement 。
您可能需要為此pip install lxml
( lxml
是用於解析的python庫)。
import requests
from bs4 import BeautifulSoup
import os
def update_url(url):
return # return updated url
req = requests.get('https://www.census.gov/programs-surveys/popest.html')
assert req.status_code == 200, f"Request returned with status {req.status_code}"
soup = BeautifulSoup(req.content, "lxml")
links = set([a['href'] for a in soup.find_all('a',href = True)])
l = list():
with open('file_name.csv', 'w', newline='') as file:
writer = csv.writer(file, delimiter=',', lineterminator='\r')
for url in links:
new_url = update_url(url) # treat them as you wish
writer.writerow(new_url) # write url to csv
# with statement closes file automatically
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.