每次来自BeautifulSoup的结果都不同

时间:2016-07-30 03:53:41

标签: python beautifulsoup

我正在网站上搜索122个不同的网页,每页有10个条目。代码在随机页面上,每次运行时随机条目中断。我可以在网址上运行一次代码,但有时它不会运行。

def get_soup(url):
    soup = BeautifulSoup(requests.get(url).content, 'html.parser')
    return soup

def from_soup(soup, myCellsList):
    cellsList = soup.find_all('li', {'class' : 'product clearfix'})
    for i in range (len(cellsList)): 
        ottdDict = {} 
        ottdDict['Name'] = cellsList[i].h3.text.strip() 

这只是我的代码的一部分,但这是发生错误的地方。问题是当我使用这个代码时,h3标签并不总是出现在cellsList中的每个项目中。当运行代码的最后一行时,这会导致NoneType错误。但是,当我检查网页时,h3标记始终存在于HTML中。

cellsList vs html 1

same comparison made from subsequent soup request

可能导致这些差异的原因是什么?我如何避免这个问题?我能够成功运行代码一段时间,它似乎突然停止工作。代码能够毫无问题地抓取一些页面,但随机页面上的随机条目上没有注册h3标签。

1 个答案:

答案 0 :(得分:2)

当您浏览网站页面时,各种元素的html存在轻微差异,获取名称的最佳方法实际上是选择外部div并从锚点中提取文本。

这将获得每个产品的所有信息,并将其放入密钥所在的位置' Tissue',' Cell' 等等。值是相关的描述:

import requests

from time import sleep


def from_soup(url):
    with requests.Session() as s:
        s.headers.update({
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36"})
    # id for next oage anchor.
    id_ = "#layoutcontent_2_middlecontent_0_threecolumncontent_0_content_ctl00_rptCenterColumn_dcpCenterColumn_0_ctl00_0_productRecords_0_bottomPaging_0_liNextPage_0"

    soup = BeautifulSoup(s.get(url).content)
    for li in soup.select("ul.product-list li.product.clearfix"):
        name = li.select_one("div.product-header.clearfix a").text.strip()
        d = {"name": name}
        for div in li.select("div.search-item"):
            k = div.strong.text
            d[k.rstrip(":")] = " ".join(div.text.replace(k, "", 1).split())
        yield d

    # get anchor for next page and loop until no longer there.
    nxt = soup.select_one(id_)

    # loop until mo more next page.
    while nxt:
        # sleep between requests
        sleep(.5)
        resp = s.get(nxt.a["href"])
        soup = BeautifulSoup(resp.content)
        for li in soup.select("ul.product-list li.product.clearfix"):
            name = li.select_one("div.product-header.clearfix a").text.strip()
            d = {"name": name}
            for div in li.select("div.search-item"):
                k = div.strong.text
                d[k.rstrip(":")] = " ".join(div.text.replace(k,"",1).split())
            yield d

跑完后:

for ind, h in enumerate(from_soup(
        "https://www.lgcstandards-atcc.org/Products/Cells_and_Microorganisms/Cell_Lines/Human/Alphanumeric.aspx?geo_country=gb")):
    print(ind, h)

您将看到包含所有数据的1211个词组。