这可能看起来很简单,但我无法让它工作。刚刚开始学习刮刮并遇到了这个问题。尝试在python REPL中的代码,它似乎工作,但不知道为什么当我编码它,它将无法正常工作。
这是我的代码以下顺便说一下。所以我要做的是为我的程序提取文章标题,链接和图片,这就是我在下面的内容。
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import json
beauty_result=[]
def scrape_b2():
soup = BeautifulSoup(urlopen('https://www.instyle.com/beauty'), 'lxml')
url = 'https://www.instyle.com'
for article in soup.find_all('article',class_='component tile media image-top type-article'):
for img in article.find_all('div',class_='component lazy-image thumbnail'):
for a in article.find('h3'):
beauty_result.append(json.dumps({
'title':a.get_text(strip=True),
'link':url+article.find('a')['href'],
'image':img.get('data-src')
}))
print(beauty_result)
if __name__ == '__main__':
scrape_b2()
这是我得到的错误的全部追溯:
D:\Coding\Python\webscrape env>python app.py
Traceback (most recent call last):
File "app.py", line 37, in <module> scrape_b2()
File "app.py", line 28, in scrape_b2 'title':a.get_text(strip=True),
File "D:\Coding\Tools\Anaconda3\envs\webscraper_practice\lib\site-packages\bs4\element.py", line 742, in getattr self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'get_text'
这就是我解决它:
def scrape_b2():
soup = BeautifulSoup(urlopen('https://www.instyle.com/beauty'), 'lxml')
url = 'https://www.instyle.com'
for article in soup.find_all('article',class_='component tile media image-top type-article'):
for img in article.find_all('div',class_='component lazy-image thumbnail'):
h3 = article.find('h3')
a_link = h3.find('a')
beauty_result.append(json.dumps({
'title': a_link.get_text(strip=True),
'link': url + a_link.get('href'),
'image': img.get('data-src')
}))
print(beauty_result)
您的错误是因为您无法使用特定于Bs4对象的get_text()
方法。
你能做的是:
h3 = article.find('h3')
a_link = h3.find('a')
beauty_result.append(json.dumps({
'title': a_link.get_text(strip=True),
'link': url + a_link.get('href'),
'image': img.get('data-src')
}))
前面的代码替换了循环for a in article.find('h3'):
以下脚本将为您提供该站点的不同文章标题及其相关链接。看起来该页面的具体内容是动态生成的,但实际上并非如此。它们存在于具有不同类名的页面源中。
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
URL = "https://www.instyle.com/beauty"
def get_article_info(link):
res = requests.get(link)
soup = BeautifulSoup(res.text, 'lxml')
for article in soup.select('.media-body h3.headline a[href^="/"]'):
title = article.get_text().strip()
link = urljoin(link,article.get("href").strip())
yield {"title":title,"url":link}
if __name__ == '__main__':
for item in get_article_info(URL):
print(item['title'],item['url'])