简体   繁体   English

如果在多个页面之间循环时页面上不存在元素,则跳过项目-BeautifulSoup和Python

[英]Skip Over Item if element doesn't exist on page when looping through multiple pages - BeautifulSoup and Python

I have a script that loops through multiple pages of a website and I want to skip over or add a blank space for the item that might not be on certain pages. 我有一个遍历网站多个页面的脚本,并且我想跳过或添加空白页面上可能没有的项目的空格。 For example, there are some pages that do not contain a license. 例如,有些页面不包含许可证。 When I run into one of those pages I get an attribute error. 当我遇到这些页面之一时,出现属性错误。 My script below loops through the first two pages with no problem, but when it hits the third page it stops. 我的以下脚本可以毫无问题地循环浏览前两页,但是当它到达第三页时,它将停止。 How can I fix this? 我怎样才能解决这个问题? Here is my script: 这是我的脚本:

from urllib.request import urlopen
from bs4 import BeautifulSoup as soup
import json

base_url = "https://open.umn.edu/opentextbooks/"

data = []
n = 50
for i in range(4, n+1):
   response = urlopen(base_url + "BookDetail.aspx?bookId=" + str(i))
   page_html = response.read()
   response.close()

   #html parsing
   page_soup = soup(page_html, "html.parser")

   #grabs info for each textbook
   containers = page_soup.findAll("div",{"class":"LongDescription"})
   author = page_soup.select("p")

   for container in containers:
       item = {}
       item['type'] = "Textbook"
       item['title'] = container.find("div",{"class":"twothird"}).h1.text
       item['author'] = author[3].get_text(separator=', ')
       if item['author'] == " ":
          item['author'] = "University of Minnesota Libraries Publishing"
       item['link'] = "https://open.umn.edu/opentextbooks/BookDetail.aspx?bookId=" + str(i)
       item['source'] = "Open Textbook Library"
       item['base_url'] = "https://open.umn.edu/opentextbooks/"
       item['license'] = container.find("p",{"class":"Badge-Condition"}).a.text
       if item['license'] != container.find("p",{"class":"Badge-Condition"}).a.text:
          item['license'] = ""
       item['license_url'] = container.find("p",{"class":"Badge-Condition"}).a["href"]
       data.append(item) # add the item to the list

   with open("./json/noSubject/otl-loop.json", "w") as writeJSON:
      json.dump(data, writeJSON, ensure_ascii=False)

I figured it out. 我想到了。 My main issue was with item['license'] Here is my fix: 我的主要问题是item['license']这是我的解决方法:

if container.find("p",{"class":"Badge-Condition"}).a:
        item['license'] = container.find("p",{"class":"Badge-Condition"}).a.text
if container.find("img",{"class":"ctl00_maincontent_imgLicence"}):
        item['license'] = ''
if container.find("p",{"class":"Badge-Condition"}).a:
        item['license_url'] = container.find("p",{"class":"Badge-Condition"}).a["href"]
if container.find("img",{"class":"ctl00_maincontent_imgLicence"}):
        item['license_url'] = ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM