【发布时间】:2014-04-13 21:41:49
【问题描述】:
我有一个充满 html 文件的文件夹,我正在尝试抓取所有指向不同页面的 url,并将这些 url 保存到 CSV 文件中。
我在 Stackoverflow 上阅读过,并尝试修改我之前使用的代码,但没有成功。 Python 正在遍历文件,但无法获取我需要的数据。
我在一个月前编写了我的第一个 Python 代码,所以我还是个菜鸟,希望有人能提供帮助!
我一直在使用的代码:
from bs4 import BeautifulSoup
import csv
import urllib2
import os
def processData( pageFile ):
f = open(pageFile, "r")
page = f.read()
f.close()
soup = BeautifulSoup(page)
urldata = soup.findAll('a', {'href': True})
urls = []
for html in urldata:
html = soup('<body><a href="123">qwe</a><a href="456">asd</a></body>')
csvfile = open('url.csv', 'ab')
writer = csv.writer(csvfile)
for url in zip(urls):
writer.writerow([url])
csvfile.close()
dir = "myurlfiles"
csvFile = "url.csv"
csvfile = open(csvFile, 'wb')
writer = csv.writer(csvfile)
writer.writerow(["URLS"])
csvfile.close()
fileList = os.listdir(dir)
totalLen = len(fileList)
count = 1
for htmlFile in fileList:
path = os.path.join(dir, htmlFile) # get the file path
processData(path) # process the data in the file
print "Processed '" + path + "'(" + str(count) + "/" + str(totalLen) + ")..."
count = count + 1
url以如下方式存储在html代码中:
<div class="item" style="overflow: hidden;">
<div class="item_image" style="width: 180px; height: 125px;" id="image_255"><a href="https://silkroad6ownowfk.onion.to/items/200mg-high-quality-dmt" style="display: block; width: 180px; height: 125px;"></a></div>
<div class="item_body">
<div class="item_title"><a href="https://silkroad6ownowfk.onion.to/items/200mg-high-quality-dmt">200mg High Quality DMT</a></div>
<div class="item_details">
vendor: <a href="https://silkroad6ownowfk.onion.to/users/ringo-deathstarr">ringo deathstarr</a><br>
ships from: United States<br>
ships to: Worldwide
</div>
</div>
<div class="item_price">
<div class="price_big">฿0.031052</div>
<a href="https://silkroad6ownowfk.onion.to/items/200mg-high-quality-dmt#shipping">add to cart</a>
</div>
【问题讨论】:
标签: python python-2.7 web-scraping html-parsing beautifulsoup