【问题标题】:Beautifulsoup and amending a listBeautifulsoup 和修改列表
【发布时间】:2017-03-14 19:06:52
【问题描述】:

我开始了解我的第一门编程语言,但在尝试使用 BS4 和 Python 的练习时遇到了一点问题。

我试图抓取的页面位于以下链接的下方: https://www.aisc.org/certification/certified-company-search2/certified-company-search/?companyName=&country=select&city=&state=&canState=&zipCode=&radius=&certification=&certs=&pageSize=10&sort=aCompany

如果您单击从列表中生成的任何链接,特定公司的 url 将变为: https://www.aisc.org/certification/certified-company?id=3220678

我正在尝试做的是抓取数据,它不是表格形式,并将其转换为带有公司名称的 excel csv 文件,然后在其自己的列中(即地址)中关于公司信息的每一行、电话、电子邮件等)。我已设法将公司名称和公司信息分开,但我无法将公司名称添加到列表中。我也无法从公司信息中解析标签。如果我使用row+= line.text,那么输出就是row = ['a','d', 'd','r','e',.......]

任何帮助将不胜感激,您将在下面找到我的代码的输入和输出。

谢谢,

INPUT:
import requests
from bs4 import BeautifulSoup


page = requests.get("https://www.aisc.org/certification/certified-company?id=3220678")
print(page.status_code)
print(page.content)

soup = BeautifulSoup(page.content, 'lxml')
#print(soup.prettify())
#print(soup.find_all('ul', class_='vlist project-details-list'))
#print(soup.find_all('div', class_='unit size1of1'))

for header in soup.find_all('div', class_='unit size1of1'):
    for company in header.find_all('h1'):
        print(company.text)
for line in soup.find_all('ul', class_='vlist project-details-list'):
    row = []
    row+= line
print(row)



OUTPUT:
2-K Steel Products, Inc.
['\n', <li><strong>Address:</strong> 65 Murray Circle</li>, '\n', <li><strong>City:</strong> Ashville</li>, '\n', <li><strong>State:</strong> AL</li>, '\n', <li><strong>Zip Code:</strong>     35953</li>, '\n', <li><strong>Country:</strong> United States</li>, '\n', <li><strong>Contact:</strong> Mr. Kal Kimbrough </li>, '\n', <li><strong>Email Address:</strong> <a href="mailto:kkimbrough@2ksteel.com">kkimbrough@2ksteel.com</a></li>, '\n', <li><strong>Phone:</strong> (205) 594-5446</li>, '\n', <li><strong>Website:</strong> <a alt="2-K Steel Products, Inc." href="http://www.2ksteel.com" target="_blank">www.2ksteel.com</a></li>, '\n', <li><strong>Certification/Endorsement Types:</strong> BU</li>, '\n']

【问题讨论】:

    标签: python beautifulsoup bs4


    【解决方案1】:

    您询问的for 循环存在两个主要问题。

    1. 每次循环时,它都会将row重新初始化为[],即空列表。

    2. 您正在使用 += 附加到一个列表,这并没有达到您的预期。

    相反,您需要将初始化移到循环之前,并使用append()

    row = []
    for line in soup.find_all('ul', class_='vlist project-details-list'):
        row.append(line)
    

    当您将+= 与左侧的列表一起使用时,它期望右侧是一个序列。恰好字符串是一种序列,特别是字符。这就是您在运行代码时所看到的:您正在extending 序列中的值列表。

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 1970-01-01
      • 2017-03-23
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-02
      相关资源
      最近更新 更多