python - 似乎无法使用 Python 和 Beautiful Soup 将所有信息写入 CSV 文件

标签 python html css

我正在尝试使用 python 脚本从网站中提取特定 header 。如果我能让这个工作正常,我实际上会提取图像名称,但我想我会从一些简单的东西开始,比如标题。我可以提取标题名称并将日期保存到 csv 文件中,但不会打印标题名称。澄清一下,每次我保存时,日期都会保存到文件中,但标题名称不会。

这是我的 python 脚本:

import urllib2
from bs4 import BeautifulSoup

import csv
import time
import os

def get_html():
    opener = urllib2.build_opener(
    urllib2.HTTPRedirectHandler(),
    urllib2.HTTPHandler(debuglevel=0),    
    )

    opener.add_handler = [
        ('User-agent',
         "Mozilla/4.0 (compatible; MSIE 7.0; "
         "Windows NT 5.1; .NET CLR 2.0.50727; "
         ".NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)")

    ]

    url = "http://www.photosbywagner.com/galleryone.html"
    response = opener.open(url)
    return ''.join(response.readlines())

def get_html_sections(html):
    soup = BeautifulSoup(html)
    html_section = soup.find('div',
            attrs={'id': 'headcontainer'})
    return html_section

def parse_section_html(html):
    selected_html = get_html_sections(html)
    result = {}

    # <img />
    result['selection'] = selected_html.find('h1').contents[0]

    return result

field_order = ['date', 'info']

fields = {'date' : 'Date',
          'info' : 'Info'}

def write_row(selected_html):
    file_name = "WrittenNames" + ".csv"
    if os.access(file_name, os.F_OK):
        file_mode = 'ab'
    else:
        file_mode = 'wb'

    csv_writer = csv.DictWriter(
        open(file_name, file_mode),
        fieldnames=field_order,
        extrasaction='ignore',
    )

    if file_mode == 'wb':
        csv_writer.writerow(fields)
    csv_writer.writerow(selected_html)


if __name__ == '__main__':
    html = get_html()
    row_to_write = parse_section_html(html)  
    row_to_write['date'] = time.strftime("%Y-%m-%d %H:%M")
    write_row(row_to_write)
    print row_to_write

这是网页:

http://www.photosbywagner.com/galleryone.html

我要拉的部分是:

<div id="headcontainer"><h1>Ed Wagner Photo Gallery:</h1></div>

我不确定我在这里遗漏了什么,因为其他一切似乎都已检查 - 它会提取正确的信息并将其打印到屏幕上,只是不会保存到 CSV 文件中。

谢谢。

最佳答案

在 parse_section_html 中,应该:

result['selection'] = selected_html.find('h1').contents[0]

成为:

result['info'] = selected_html.find('h1').contents[0]

匹配您的字段定义?

关于python - 似乎无法使用 Python 和 Beautiful Soup 将所有信息写入 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18177422/

相关文章:

html - 为什么 <a> 标签不适合子图像

html - 文本仅在图像下方而不是在另一个分辨率之间

python - 删除Python中的列

python - Matplotlib - 如何为具有对数刻度的线图设置颜色条

javascript - React Material UI 表添加自定义按钮

HTML 元素与 Internet Explorer 中的其他元素不完全一致

javascript - 即使刷新也保留所选选项的值

html - Bootstrap/HTML - 使用 Accordion 和 Bootstrap 网格

python - 如何同时监控loss和val_loss以避免神经网络对训练集或测试集过度拟合?

Python音频分析: find real time values of the strongest beat in each meter