【发布时间】:2019-09-21 06:44:45
【问题描述】:
我正在尝试构建一个爬虫来获取一些学术论文的摘要及其相应的标题on this page。
问题是我的for link in bsObj.findAll('a',{'class':'search-track'}) 没有返回我需要进一步构建刮板的链接。在我的代码中,检查是这样的:
for link in bsObj.findAll('a',{'class':'search-track'}):
print(link)
上面的 for 循环确实会打印出任何内容,但是,href 链接应该在 <a class="search-track" ...</a> 内。
我提到了this post,但是更改 Beautifulsoup 解析器并不能解决我的代码问题。我在 Beautifulsoup 构造函数中使用"html.parser":bsObj = bs(html.content, features="html.parser")。
print(len(bsObj)) 打印出“3”,同时为"lxml" 和"html5lib" 打印出“2”。
另外,我开始使用urllib.request.urlopen 来获取页面,然后尝试使用requests.get()。不幸的是,这两种方法给了我相同的bsObj。
这是我写的代码:
#from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup as bs
import ssl
'''
The elsevier search is kind of a tree structure:
"keyword --> a list of journals (a journal contain many articles) --> lists of articles
'''
address = input("Please type in your keyword: ") #My keyword is catalyst for water splitting
#https://www.elsevier.com/en-xs/search-results?
#query=catalyst%20for%20water%20splitting&labels=journals&page=1
address = address.replace(" ", "%20")
address = "https://www.elsevier.com/en-xs/search-results?query=" + address + "&labels=journals&page=1"
journals = []
articles = []
def getJournals(url):
global journals
#html = urlopen(url)
html = requests.get(url)
bsObj = bs(html.content, features="html.parser")
#print(len(bsObj))
#testFile = open('testFile.txt', 'wb')
#testFile.write(bsObj.text.encode(encoding='utf-8', errors='strict') +'\n'.encode(encoding='utf-8', errors='strict'))
#testFile.close()
for link in bsObj.findAll('a',{'class':'search-track'}):
print(link)
########does not print anything########
'''
if 'href' in link.attrs and link.attrs['href'] not in journals:
newJournal = link.attrs['href']
journals.append(newJournal)
'''
return None
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
getJournals(address)
print(journals)
谁能告诉我代码中for循环没有打印出任何链接的问题是什么?我需要将期刊的链接存储在一个列表中,然后访问每个链接以抓取论文摘要。按理说,论文的摘要部分是免费的,网站不应该因此屏蔽我的 ID。
【问题讨论】:
-
你能简单地发布
html = requests.get(url)使用的确切网址吗? -
@JackFleeting 链接在这里:elsevier.com/en-xs/…
标签: python url web-scraping beautifulsoup python-requests