簡體   English   中英

從csv中的URL抓取HTML,然后使用python打印到csv

[英]Scraping HTML from URLs in csv then printing to csv with python

我正在嘗試在csv中的一系列URL上抓取日期,然后將日期輸出到新的CSV。

我有基本的python代碼,但無法弄清楚如何加載CSV(而不是從數組中提取)並抓取每個url,然后將其輸出到新的CSV。 通過閱讀幾篇文章,我認為我想使用csv python模塊,但無法正常工作。

這是我的抓取代碼

import urllib
import re

exampleurls =["http://www.domain1.com","http://www.domain2.com","http://www.domain3.com"]

i=0
while i<len(exampleurls):
    url = exampleurls[i]
    htmlfile = urllib.urlopen(url)
    htmltext = htmlfile.read()
    regex = 'on [0-9][0-9]\.[0-9][0-9]\.[0-9][0-9]'
    pattern = re.compile(regex)
    date = re.findall(pattern,htmltext)
    print date
    i+=1

任何幫助深表感謝!

如果您的csv看起來像這樣:

"http://www.domain1.com","other column","yet another"
"http://www.domain2.com","other column","yet another"
...

像這樣提取域:

import urllib
import csv

with open('urlFile.csv') as f:
    reader = csv.reader(f)

    for rec in reader:
        htmlfile = urllib.urlopen(rec[0])
        ...

如果您的網址文件看起來像這樣:

http://www.domain1.com
http://www.domain2.com
...

您可以通過以下列表理解來做一些更酷的事情:

urls = [x for x in open('urlFile')]

編輯:回復評論

您可以像這樣在python中打開文件:

f = open('myurls.csv', 'w')
...
for rec in reader:
    ...
    f.write(urlstring)
f.close()

或者,如果您使用的是unix / linux,則在代碼中使用print,然后在bash中使用:

python your_scraping_script.py > someoutfile.csv

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM