我是一名初学者python程序员,我正在尝试将webcrawler作为练习。 目前我正面临一个问题,我找不到合适的解决方案。问题是,我试图从没有课程的页面获取链接地址/地址,因此我不知道如何过滤该特定链接。 这可能是更好的展示给你。
The page I am trying to get the link from.
正如您所看到的,我试图获取“历史价格”链接的href属性中的内容。这里是我的Python代码:Python - 如何在没有课程的网页上找到链接?
import requests
from bs4 import BeautifulSoup
def find_historicalprices_link(url):
source = requests.get(url)
text = source.text
soup = BeautifulSoup(text, 'html.parser')
link = soup.find_all('li', 'fjfe-nav-sub')
href = str(link.get('href'))
find_spreadsheet(href)
def find_spreadsheet(url):
source = requests.get(url)
text = source.text
soup = BeautifulSoup(text, 'html.parser')
link = soup.find('a', {'class' : 'nowrap'})
href = str(link.get('href'))
download_spreadsheet(href)
def download_spreadsheet(url):
response = requests.get(url)
text = response.text
lines = text.split("\\n")
filename = r'google.csv'
file = open(filename, 'w')
for line in lines:
file.write(line + "\n")
file.close()
find_historicalprices_link('https://www.google.com/finance?q=NASDAQ%3AGOOGL&ei=3lowWYGRJNSvsgGPgaywDw')
在功能“find_spreadsheet(URL)”,我可以很容易地通过寻找所谓的“NOWRAP”类过滤器的链接。不幸的是,历史价格的链接没有这样的类而现在我的剧本只是给了我以下错误:
AttributeError: ResultSet object has no attribute 'get'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()?
如何确保我的爬虫只需要在href从“历史价格”?
预先感谢您。
更新:
我找到了办法。通过只查找附加了特定文本的链接,我可以找到我需要的href。
解决方案:
soup.find( 'A',字符串= “历史价格”)
你看了你的错误?此行在这里引起你的问题:link = soup.find_all('li','fjfe-nav-sub') href = str(link.get('href'))链接是一个列表,而不是一个元素 – jarcobi889
@ jarcobi889好的,那么我需要做些什么来解决这个问题呢?我已经改变find_all()找到(),现在它只是返回“无” –