【问题标题】:Python BeautifulSoup unable to find the correct data; invalid syntax error for "class"Python BeautifulSoup 无法找到正确的数据; “类”的无效语法错误
【发布时间】:2020-05-11 15:45:06
【问题描述】:

我是最后才来的。我无法获取此代码来提取正确的数据。它似乎根本找不到它。请帮忙。

目标是从网站上提取姓名和电话号码并将它们放入 CSV。

import requests
from bs4 import BeautifulSoup
import csv

def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    target = soup.select("div.result-item")
    with open("Output.csv", 'a', newline="") as f:
        writer = csv.writer(f)
        writer.writerow(["Name", "Phone"])
        for tar in target:
            name = tar.find("div", class="result-name").text
            phone = tar.find("div", class="result-phone").text
            writer.writerow([name, phone])

urllink = "http://www.reinboundlogistics.com/cms/search-tool/3pl/"


main(urllink)

我得到这个结果:

File "program1.py", line 13
    name = tar.find("div", class="result-name").text
                           ^
SyntaxError: invalid syntax

我似乎无法弄清楚为什么会向我抛出这个语法错误,因为我之前成功使用过几乎相同的代码。唯一的区别是我使用了“itemprop=”而不是“class=”。

请就如何改进或提高我准确定位所需数据的方法提出建议。

【问题讨论】:

  • class 是保留关键字,这是错误的原因。

标签: python html beautifulsoup syntax


【解决方案1】:

类是关键字。将其更改为

name = tar.find("div", class_="result-name").text
phone = tar.find("div", class_="result-phone").text

name = tar.find("div", attrs={"class" :"result-name"}).text
phone = tar.find("div", attrs={"class" :"result-phone"}).text

【讨论】:

    猜你喜欢
    • 2012-06-18
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 2013-08-08
    • 2022-12-24
    相关资源
    最近更新 更多