无法使用beautifulsoup抓取日语网站

时间:2019-09-18 01:05:10

标签: python html beautifulsoup python-requests

我尝试通过在线尝试一些简单的教程来删除日语网站,但无法从该网站获取信息。下面是我的代码:

import requests
wiki = "https://www.athome.co.jp/chintai/1001303243/?DOWN=2&BKLISTID=002LPC&sref=list_simple&bi=tatemono"
page = requests.get(wiki)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page.text, 'lxml')
for i in soup.findAll('data payments'):
    print(i.text)

我想从以下部分中获得

                <dl class="data payments">
                    <dt>賃料:</dt>
                    <dd><span class="num">7.3万円</span></dd>
                </dl>

我希望打印我们的数据付款,即价格为“ 7.3万円”的“充料”。

期望(以字符串形式):

“付款:联邦料为7.3万円”

编辑:

import requests
wiki = "https://www.athome.co.jp/"
headers = requests.utils.default_headers()
headers.update({
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',
})
page = requests.get(wiki,headers=headers)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'lxml')
print(soup.decode('utf-8', 'replace'))

3 个答案:

答案 0 :(得分:2)

在最新版本的代码中,您对汤进行解码,并且您将无法在BeautifulSoup中使用诸如findfind_all之类的功能。但是我们稍后再讨论。

开始

获取汤后,您可以打印汤,您将看到:(仅显示关键部分)

<meta content="NOINDEX, NOFOLLOW" name="ROBOTS"/>
<meta content="0" http-equiv="expires"/>
<meta content="Tue, 01 Jan 1980 1:00:00 GMT" http-equiv="expires"/>
<meta content="10; url=/distil_r_captcha.html?requestId=2ac19293-8282-4602-8bf5-126d194a4827&amp;httpReferrer=%2Fchintai%2F1001303243%2F%3FDOWN%3D2%26BKLISTID%3D002LPC%26sref%3Dlist_simple%26bi%3Dtatemono" http-equiv="refresh"/>

这意味着您没有获得足够的元素,并且被视为爬网程序。

因此,@ KunduK的答案中缺少某些内容,与find函数无关。

主要部分

首先,您需要使python脚本不像爬虫那样。

标题

标头最常用于检测攻击者。 在原始请求中,当您从请求中获得会话时,可以使用以下命令检查标头:

>>> s = requests.session()
>>> print(s.headers)
{'User-Agent': 'python-requests/2.22.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

您可以看到此处的标头将告诉服务器您是一个搜寻器程序,即python-requests/2.22.0

因此,您需要使用更新标头来修改User-Agent

s = requests.session()
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
}
s.headers.update(headers)

但是,在测试爬虫时,仍然将其检测为爬虫。因此,我们需要在头部分中进一步挖掘。 (但这可能是其他原因,例如IP阻止程序或Cookie的原因。我稍后会提及。)

在Chrome中,我们打开开发人员工具,然后打开网站。 (要假装这是您第一次访问该网站,最好先clear the cookies。)清除cookie后,刷新页面。我们可以在开发人员工具的网卡中看到,其中显示了许多来自Chrome的请求。 Developer Tools in Chrome

通过输入第一个属性https://www.athome.co.jp/,我们可以在右侧看到一个详细表,其中请求标头是Chrome生成的标头,用于请求目标站点的服务器。 Detailed Page of Network Card

为确保一切正常,您只需在此Chrome标头中将所有内容添加到抓取工具中,就无法再确定您是真正的Chrome或抓取工具了。 (对于大多数网站,但我也发现有些网站使用starnge设置,每个请求中都需要一个特殊的标头。)

我已经发现,在添加accept-language之后,该网站的反爬虫功能将使您通过。

因此,总的来说,您需要像这样更新标头。

headers = {
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
}
s.headers.update(headers)

饼干

有关cookie的说明,您可以参考wiki。 要获取Cookie,有一种简单的方法。 首先,启动一个会话并更新标题,就像我上面提到的那样。 其次,请求获取页面https://www.athome.co.jp,获取页面后,您将获得服务器发布的cookie。

s.get(url='https://www.athome.co.jp')

requests.session的优点是会话将帮助您维护cookie,因此您的下一个请求将自动使用此cookie。

您可以仅使用以下方法检查获得的cookie:

print(s.cookies)

我的结果是:

<RequestsCookieJar[Cookie(version=0, name='athome_lab', value='ffba98ff.592d4d027d28b', port=None, port_specified=False, domain='www.athome.co.jp', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=1884177606, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]>

您不需要解析此页面,因为您只需要Cookie而不是内容。

获取内容

您可以仅使用获取的会话来请求您提到的wiki page

wiki = "https://www.athome.co.jp/chintai/1001303243/?DOWN=2&BKLISTID=002LPC&sref=list_simple&bi=tatemono"
page = s.get(wiki)

现在,您想要的所有内容都将由服务器发布给您,您可以使用BeautifulSoup对其进行解析。

from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')

获取所需的内容后,可以使用BeautifulSoup获取目标元素。

soup.find('dl', attrs={'class': 'data payments'})

您将获得的是:

<dl class="data payments">
<dt>賃料:</dt>
<dd><span class="num">7.3万円</span></dd>
</dl>

您可以从中提取所需的信息。

target_content = soup.find('dl', attrs={'class': 'data payments'})
dt = target_content.find('dt').get_text()
dd = target_content.find('dd').get_text()

将其格式化为一行。

print('payment: {dt} is {dd}'.format(dt=dt[:-1], dd=dd))

一切都已完成。

摘要

我将在下面粘贴代码。

# Import packages you want.
import requests
from bs4 import BeautifulSoup

# Initiate a session and update the headers.
s = requests.session()
headers = {
    'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36',
}
s.headers.update(headers)

# Get the homepage of the website and get cookies.
s.get(url='https://www.athome.co.jp')
"""
# You might need to use the following part to check if you have successfully obtained the cookies. 
# If not, you might be blocked by the anti-cralwer.
print(s.cookies)
"""
# Get the content from the page.
wiki = "https://www.athome.co.jp/chintai/1001303243/?DOWN=2&BKLISTID=002LPC&sref=list_simple&bi=tatemono"
page = s.get(wiki)

# Parse the webpage for getting the elements.
soup = BeautifulSoup(page.content, 'html.parser')
target_content = soup.find('dl', attrs={'class': 'data payments'})
dt = target_content.find('dt').get_text()
dd = target_content.find('dd').get_text()

# Print the result.
print('payment: {dt} is {dd}'.format(dt=dt[:-1], dd=dd))

在搜寻器字段中,还有很长的路要走。

最好获取它的在线信息,并充分利用浏览器中的开发人员工具

您可能需要找出内容是否由JavaScript加载,或者内容是否在iframe中。

此外,您可能会被视为爬虫,并被服务器阻止。只能通过更频繁地进行编码才能获得反爬虫技术。

我建议您从一个更简单的网站开始,而该网站应该没有反爬行功能。

答案 1 :(得分:1)

尝试下面的代码。使用带有标签的类名来查找元素。

from bs4 import BeautifulSoup
import requests
wiki = "https://www.athome.co.jp/chintai/1001303243/?DOWN=2&BKLISTID=002LPC&sref=list_simple&bi=tatemono"
headers = requests.utils.default_headers()
headers.update({
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',
})
page = requests.get(wiki,headers=headers)

soup = BeautifulSoup(page.content, 'lxml')

for i in soup.find_all("dl",class_="data payments"):
   print(i.find('dt').text)
   print(i.find('span').text)

输出:

賃料:
7.3万円

如果要操纵预期的输出,请尝试。

from bs4 import BeautifulSoup
import requests
wiki = "https://www.athome.co.jp/chintai/1001303243/?DOWN=2&BKLISTID=002LPC&sref=list_simple&bi=tatemono"
headers = requests.utils.default_headers()
headers.update({
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',
})
page = requests.get(wiki,headers=headers)

soup = BeautifulSoup(page.content, 'lxml')

for i in soup.find_all("dl",class_="data payments"):
   print("Payment: " + i.find('dt').text.split(':')[0] + " is " + i.find('span').text)

输出

Payment: 賃料 is 7.3万円

答案 2 :(得分:0)

您遇到的问题是,由于该站点将其标识为来自机器人,因此该站点阻止了您的请求。

通常的方法是附加浏览器在请求中发送的相同标头(包括cookie)。如果您转到Inspect > Network > Request > Copy > Copy as Curl,则可以看到Chrome发送的所有标头。

运行脚本时,您将得到以下信息:

You reached this page when attempting to access https://www.athome.co.jp/chintai/1001303243/?DOWN=2&BKLISTID=002LPC&sref=list_simple&bi=tatemono from 152.172.223.133 on 2019-09-18 02:21:34 UTC.
相关问题