【发布时间】:2013-12-24 21:09:38
【问题描述】:
from bs4 import BeautifulSoup
import codecs
import sys
import urllib.request
site_response= urllib.request.urlopen("http://site/")
html=site_response.read()
file = open ("cars.html","wb") #open file in binary mode
file.write(html)
file.close()
soup = BeautifulSoup(open("cars.html"))
output = (soup.prettify('latin'))
#print(output) #prints whole file for testing
file_output = open ("cars_out.txt","wb")
file_output.write(output)
file_output.close()
fulllist=soup.find_all("div", class_="row vehicle")
#print(fulllist) #prints each row vehicle class for debug
for item in fulllist:
item_print=item.find("span", class_="modelYearSort").string
item_print=item_print + "|" + item.find("span", class_="mmtSort").string
seller_phone=item.find("span", class_="seller-phone")
print(seller_phone)
# item_print=item_print + "|" + item.find("span", class_="seller-phone").string
item_print=item_print + "|" + item.find("span", class_="priceSort").string
item_print=item_print + "|" + item.find("span", class_="milesSort").string
print(item_print)
我有上面的代码,它会解析一些 html 代码并生成一个管道划定文件。它工作正常,除了有一些条目在 html 代码中缺少其中一个元素(卖家电话)。并非所有条目都有卖家电话号码。
item.find("span", class_="seller-phone").string
我在这里失败了。当卖家电话丢失时,线路故障我并不感到惊讶。我得到 'AttributeError' NoneType 对象没有属性字符串。
我可以在没有 '.string' 的情况下执行 'item.find' 并取回完整的 html 块。但我不知道如何为这些情况提取文本。
【问题讨论】:
标签: python python-3.x beautifulsoup