【问题标题】:trying to extract data and want to save in excel but getting error using python beautifulsoup尝试提取数据并希望保存在 excel 中,但使用 python beautifulsoup 时出错
【发布时间】:2019-04-19 16:00:51
【问题描述】:

试图提取但最后一个字段出现错误想要将所有字段保存在 excel 中。

我尝试使用beautifulsoup 提取但未能捕获,出现以下错误

Traceback(最近一次调用最后一次):

文件“C:/Users/acer/AppData/Local/Programs/Python/Python37/agri.py”,第 30 行,在

标本=soup2.find('h3',class_='触发器

expanded').find_next_sibling('div',class_='collapsefaq-content').text

AttributeError: 'NoneType' 对象没有属性 'find_next_sibling'

from bs4 import BeautifulSoup
import requests

page1 = requests.get('http://www.agriculture.gov.au/pests-diseases-weeds/plant#identify-pests-diseases')

soup1 = BeautifulSoup(page1.text,'lxml')

for lis in soup1.find_all('li',class_='flex-item'):
    diseases = lis.find('img').next_sibling
    print("Diseases: " + diseases)
    image_link = lis.find('img')['src']
    print("Image_Link:http://www.agriculture.gov.au" + image_link)
    links = lis.find('a')['href']
    if links.startswith("http://"):
        link = links
    else:
        link = "http://www.agriculture.gov.au" + links
    page2 = requests.get(link)
    soup2 = BeautifulSoup(page2.text,'lxml')

    try:
        origin = soup2.find('strong',string='Origin: ').next_sibling
        print("Origin: " + origin)
    except:
        pass
    try:
        imported = soup2.find('strong',string='Pathways: ').next_sibling
        print("Imported: " + imported)
    except:
        pass 
    specimens = soup2.find('h3',class_='trigger expanded').find_next_sibling('div',class_='collapsefaq-content').text
    print("Specimens: " + specimens)

想提取最后一个字段并使用 python 将所有字段保存到 excel 表中,请帮助我。

【问题讨论】:

    标签: html python-3.x web-scraping beautifulsoup


    【解决方案1】:

    小错误:

       data2,append("Image_Link:http://www.agriculture.gov.au" + image_link)
    

    应该是:

       data2.append("Image_Link:http://www.agriculture.gov.au" + image_link) #period instead of a comma
    

    【讨论】:

      【解决方案2】:

      似乎希望页眉防止被阻止,并且每个页面都没有样本部分。下面显示了每个页面对样本信息的可能处理

      from bs4 import BeautifulSoup
      import requests
      import pandas as pd
      
      base = 'http://www.agriculture.gov.au'
      headers = {'User-Agent' : 'Mozilla/5.0'}
      specimens = []
      with requests.Session() as s:
          r = s.get('http://www.agriculture.gov.au/pests-diseases-weeds/plant#identify-pests-diseases', headers = headers)
          soup = BeautifulSoup(r.content, 'lxml')
          names, images, links = zip(*[ ( item.text.strip(), base + item.select_one('img')['src'] , item['href'] if 'http' in item['href'] else base + item['href']) for item in soup.select('.flex-item > a') ])
          for link in links:
              r = s.get(link)
              soup = BeautifulSoup(r.content, 'lxml')
              if soup.select_one('.trigger'): # could also use if soup.select_one('.trigger:nth-of-type(3) + div'):
                  info = soup.select_one('.trigger:nth-of-type(3) + div').text
              else:
                  info = 'None'
              specimens.append(info)
      
      df = pd.DataFrame([names, images, links, specimens])
      df = df.transpose()
      df.columns  = ['names', 'image_link', 'link', 'specimen']
      df.to_csv(r"C:\Users\User\Desktop\Data.csv", sep=',', encoding='utf-8-sig',index = False ) 
      

      我已经运行了很多次没有问题,但是,你总是可以将我当前的测试切换到 try except 块。

      from bs4 import BeautifulSoup
      import requests
      import pandas as pd
      
      base = 'http://www.agriculture.gov.au'
      headers = {'User-Agent' : 'Mozilla/5.0'}
      specimens = []
      with requests.Session() as s:
          r = s.get('http://www.agriculture.gov.au/pests-diseases-weeds/plant#identify-pests-diseases', headers = headers)
          soup = BeautifulSoup(r.content, 'lxml')
          names, images, links = zip(*[ ( item.text.strip(), base + item.select_one('img')['src'] , item['href'] if 'http' in item['href'] else base + item['href']) for item in soup.select('.flex-item > a') ])
          for link in links:
              r = s.get(link)
              soup = BeautifulSoup(r.content, 'lxml')
              try:
                  info = soup.select_one('.trigger:nth-of-type(3) + div').text
              except:
                  info = 'None'
                  print(link)
              specimens.append(info)
      
      df = pd.DataFrame([names, images, links, specimens])
      df = df.transpose()
      df.columns  = ['names', 'image_link', 'link', 'specimen']
      

      csv 输出示例:

      【讨论】:

      • 出现错误“文件“C:\Users\acer\AppData\Local\Programs\Python\Python37\agri.py”,第 16 行,在 info = soup.select_one('. trigger:nth-of-type(3) + div').text AttributeError: 'NoneType' object has no attribute 'text' "
      • 您是否完全按照上面的方式运行它? (仅更改输出文件路径)。我已经连续运行了5次没有问题。使用 try except 添加了第二个版本
      • 我运行您上面的代码并在输出屏幕中提供链接,并且此错误 "df.to_csv(r"C:\Users\acer\Desktop\Data.csv", sep=',', encoding='utf-8-sig',index = False )" "OSError: [Errno 22] 无效参数:'\u202aC:\\Users\\acer\\Desktop\\Data.csv'"
      • 您使用的是什么操作系统(该行是为 Windows 路径编写的)?另外,尝试简单地 print(df) 并在末尾注释掉 csv 写入行。 df 是否按预期打印出来?
      • 我使用的是 windows 10,在 print(df) 将输出作为名称列中的所有名称之后,第二列包含 3 个点,样本列中第三列不包含任何内容
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      相关资源
      最近更新 更多