【问题标题】:Python/BS - Getting URLs from html files stored in a directory, save to CSVPython/BS - 从存储在目录中的 html 文件中获取 URL,保存为 CSV
【发布时间】: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


    【解决方案1】:

    您可以使用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 上下文管理器。

    希望对您有所帮助。

    【讨论】:

    • 谢谢!这工作得很好,除了我得到了 URL 中的文本,而不是完整的 URL?所以不是apples.com,而是“苹果”。
    • @user3343907 好的,只需将link.text 更改为link['href']
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 2014-06-09
    • 1970-01-01
    • 2014-05-18
    • 2014-09-01
    • 2013-09-27
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多