Python美丽汤/查找

时间:2020-04-22 02:42:21

标签: python list beautifulsoup python-requests

我的问题是,当我打印出链接列表时,它会在终端中打印出一个漂亮的列表,但我不知道为什么链接(列表)不包含find方法? 而且,同样的代码正在我老师的思想上

import requests
from bs4 import BeautifulSoup

param = {'s': 'zombie'}
r = requests.get('http://chilltime.pk/search', params=param

soup = BeautifulSoup(r.text, "html.parser")
results = soup.find('tbody')
links = soup.findAll('td')

for i in links:
    item_text = i.find('a').text
    item_href = i.find('a').attrs['href']

    if item_text and item_href:
        print(item_text)
        print(item_href)
ERROR:
**Traceback (most recent call last):
File "C:/Users/AFFAN ULHAQ/PycharmProjects/Beautiful/bsp.py", line 19, in <module>
item_text = i.find('a').text
AttributeError: 'NoneType' object has no attribute 'text'**

2 个答案:

答案 0 :(得分:1)

import requests
from bs4 import BeautifulSoup

params = {
    's': 'zombie'
}

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'
}


def main(url):
    r = requests.get(url, params=params, headers=headers)
    soup = BeautifulSoup(r.content, 'html.parser')
    target = soup.findAll("a", href=True)
    for tar in target:
        print(tar.text, tar['href'])


main("http://chilltime.pk/search")

答案 1 :(得分:1)

最有可能的是,“ i”变量迭代链接没有属性“ a”,也就是说,您的html单元内没有链接。也许是您可以检查您是否确实有链接

for i in links:
    item_text = i.find('a').text if i.find('a') else False
    item_href = i.find('a').attrs['href'] if i.find('a') else False