簡體   English   中英

Python 美湯/查找

[英]Python beautiful soup/ Find

我的問題是,當我打印鏈接列表時,它會在終端中打印一個漂亮的列表,但我不知道為什么鏈接(列表)不包含 find 方法? 此外,同樣的代碼正在我老師的 ide 上工作

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'**
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")

很可能“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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM