Python/BS - 从存储在目录中的HTML文件获取URL并保存为CSV

1 投票
1 回答
900 浏览
提问于 2025-04-17 21:39

我有一个文件夹,里面全是html文件,我想从这些文件中提取出所有指向不同页面的链接,并把这些链接保存到一个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 

这些链接在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>

1 个回答

2

你可以使用 glob 这个工具,通过 *.html 的方式来找到目录下所有的 html 文件,然后用 BeautifulSoupfind_all() 方法找到所有的链接,并把它们写入一个文件(看起来这里根本不需要用到 csv 模块)。

import glob
from bs4 import BeautifulSoup


path = 'myurlfiles/*.html'

urls = []
for file_name in glob.iglob(path):
    with open(file_name) as f:
        soup = BeautifulSoup(f)
        urls += [link['href'] for link in soup.find_all('a', {'href': True})]

with open("url.csv", "wb") as f:
    f.write("\n".join(urls))

需要注意的是,在把文件传给 BeautifulSoup 的构造函数之前,你不需要先读取文件,因为它也支持类似文件的对象。此外,使用 with 上下文管理器来处理文件是个好习惯。

希望这些信息对你有帮助。

撰写回答