Skip to content

Commit d1276d0

Browse files
authored
Create python爬蟲beautifulsoup string抓取問題.md
1 parent effaafa commit d1276d0

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# python 爬蟲 beautifulsoup string 抓取問題
2+
3+
## 問題
4+
5+
![图片描述][1]
6+
7+
[1]: https://segmentfault.com/img/bVyY2I
8+
9+
我要的是這個藍色部分的內容,但是 beautifulsoup 裡兩個方法,一個 `.strings` 還有一個 `get_text()` 都不行,他們會把下面 `span` 裡的 `string:Good Sister-in-lwa:Forbidden love` 這些都抓取。
10+
11+
`.string` 直接抓不到,因為這個方法無法判斷該抓取哪個 string。
12+
13+
所以我該怎麼解決標籤里內嵌標籤的抓取字符串問題
14+
15+
問題出自 [segmentfault](https://segmentfault.com/q/1010000005915466/a-1020000005915727), by [yikosudo](https://segmentfault.com/u/yikosudo)
16+
17+
## 回答
18+
19+
@洛克 的想法不錯,把不要的標籤淬出或是移除,再取字串:
20+
21+
```python
22+
>>> from bs4 import BeautifulSoup
23+
>>> html = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
24+
>>> soup = BeautifulSoup(html)
25+
>>> a_tag = soup.a
26+
>>> i_tag = soup.i.extract()
27+
>>> a_tag.string
28+
'I linked to '
29+
```
30+
31+
或是像 @cloverstd 說的:
32+
33+
```
34+
>>> from bs4 import BeautifulSoup
35+
>>> html = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
36+
>>> soup = BeautifulSoup(html)
37+
>>> a_tag = soup.a
38+
>>> list(a_tag.strings)
39+
[u'I linked to ', u'example.com']
40+
>>> list(a_tag.strings)[0]
41+
'I linked to '
42+
>>> a_tag.contents[0]
43+
'I linked to '
44+
```
45+
46+
總之方法很多,任意組合囉...

0 commit comments

Comments
 (0)