【问题标题】:Parsing span with beautiful soup用漂亮的汤解析 span
【发布时间】:2019-11-10 06:47:50
【问题描述】:

我正在尝试解析某个网站,试图找到 div 标签和 class_ 中的“span”。 Span 在特定类中,如果等于字符串,例如“line”,则返回网站的实际链接。

我收到的错误消息:

第 28 行,在 soup = BeautifulSoup(url_html,"html.parser") 第 245 行,在 init 中 elif len(markup)

import csv
from bs4 import BeautifulSoup
import requests

contents = []

def condition_check():
    for sp in soup.find("div",class_='-vDIg'):
        check = sp.span
        if check in ['Line','LINE ID',]:
            return link


filename = 'link_business_filter.csv'

with(open(filename,'rt')) as f:
    data = csv.reader(f)

    for row in data:
        links = row[0]
        contents.append(links)



for link in contents:
    url_html = requests.get(link)
    soup = BeautifulSoup(url_html,"html.parser")
    con_fltr = condition_check()
    print(con_fltr)

【问题讨论】:

  • soup = BeautifulSoup(url_html.text,"html.parser")?
  • 也发布那个 html sn-p,以及你特别想要什么目标值
  • 看起来你的对象初始化有问题。您可能应该检查requests.get() 的返回类型。我认为要获得实际的 HTML 表示,您需要执行 url_html.content 或类似的操作。阅读requests 的文档。
  • @Rakesh 添加 soup = BeautifulSoup(url_html.text,"html.parser") 第 30 行,在 con_fltr = condition_check() in condition_check for sp in soup.find("div" ,class_="-vDIg"):
  • 这并没有说明实际错误是什么。它只说它发生的位置。我的直觉是find 只返回第一个元素。您需要findAll 进行迭代。

标签: python beautifulsoup python-requests


【解决方案1】:

您将 Request 对象传递给 Beautiful Soup,您需要像这样传递 html 内容:

for link in contents:
    url_html = requests.get(link)
    soup = BeautifulSoup(url_html.content,"html.parser")
    con_fltr = condition_check()
    print(con_fltr)

url_html --> url_html.content

【讨论】:

  • 我添加了 soup = BeautifulSoup(url_html.content,"html.parser") 错误现在我得到了这个 >> 第 30 行,在 con_fltr = condition_check(),, 第 8 行,在 soup.find("div",class_="-vDIg") 中检查 sp 的条件:
  • @BhatOvasQayoom 如果要在soup.find("div",class_="-vDIg") 中查找多个元素,请将其更改为soup.find_all("div",class_="-vDIg ”)。或在这里分享整个堆栈跟踪
猜你喜欢
  • 2021-08-13
  • 2013-03-21
  • 1970-01-01
  • 2017-05-23
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2018-07-03
  • 2015-07-03
相关资源
最近更新 更多