仅以简洁的方式获取标签的字符串值的Beautifulsoup方法?

时间:2019-07-03 12:09:35

标签: beautifulsoup

当我想获取login(){ firebaselogin(userEmail2, userPass); newKey = database.push().key; firebase.auth().onAuthStateChanged(function (user) { if(user){ database.child("sessions/" + newKey).set({ userID: user.uid, connectedAt: firebase.database.ServerValue.TIMESTAMP, sessionID: newKey }).then(success => { location.href = 'logged_in.html'; }); database.child("sessions/" + newKey).onDisconnect().update({ disconnectedAt: firebase.database.ServerValue.TIMESTAMP }) } }); } 的文本时:

<Dressing>Italian</Dressing>

不幸的是,如果找不到修整节点,则会引发以下异常:

salad = BeautifulSoup(salad_response.content, 'xml')
dressing = salad.find('Dressing').string

所以我必须先检查:

*** AttributeError: 'NoneType' object has no attribute 'string'

我可以更简洁地做到这一点吗?

2 个答案:

答案 0 :(得分:0)

您可以在if条件中使用该变量。

class _MovieFlipperState extends State<MovieFlipper> {
  double scrollPercent = 0.0;
  Offset startDrag;
  double startDragPercentScroll;

  double finishScrollStart;
  double finishScrollEnd;

  AnimationController finishScrollController;

  void _onHorizontalDragStart(DragStartDetails details) {
    startDrag = details.globalPosition;
    startDragPercentScroll = scrollPercent;
  }

  void _onHorizontalDragUpdate(DragUpdateDetails details) {
    final currDrag = details.globalPosition;
    final dragDistance = currDrag.dx - startDrag.dx;
    final singleCardDragPercent = dragDistance / context.size.width;

    setState(() {
      scrollPercent = (startDragPercentScroll +
          (-singleCardDragPercent / widget.movies.length)).clamp(
          0.0, 1.0 - (1 / widget.movies.length));
    });
  }

  void _onHorizontalDragEnd(DragEndDetails details) {
    setState(() {
      startDrag = null;
      startDragPercentScroll = null;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onHorizontalDragStart: _onHorizontalDragStart,
      onHorizontalDragUpdate: _onHorizontalDragUpdate,
      onHorizontalDragEnd: _onHorizontalDragEnd,
      behavior: HitTestBehavior.translucent,
      child: Stack(
        children: _buildCards(),
      ),
    );
  }

  List<Widget> _buildCards() {
    return [
      _buildCard(0, 4, scrollPercent),
      _buildCard(1, 4, scrollPercent),
      _buildCard(2, 4, scrollPercent),
      _buildCard(3, 4, scrollPercent)
    ];
  }

  Widget _buildCard(int cardIndex, int cardCount, double scrollPercent) {
    print(scrollPercent);
    double offset = 0.05+scrollPercent;
    double xOffset = cardIndex == cardCount - 1
        ? 0
        : cardIndex == cardCount - 2
        ? offset
        : cardIndex == cardCount - 3 ? offset * 2 : offset * 5;
    double opacity = cardIndex == cardCount - 1
        ? 1
        : cardIndex == cardCount - 2
        ? 0.6
        : cardIndex == cardCount - 3 ? 0.4 : 0;
    return FractionalTranslation(
      translation: Offset(xOffset, 0.0),
      child: MovieCard(
        movie: widget.movies[cardIndex],
        opacity: opacity,
      ),
    );
  }
}

class MovieCard extends StatelessWidget {
  final Movie movie;
  final double opacity;

  const MovieCard({Key key, this.movie, this.opacity = 1}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Opacity(
      opacity: opacity,
      child: Card(
        semanticContainer: true,
        clipBehavior: Clip.antiAliasWithSaveLayer,
        child: Image.asset(
          movie.poster,
          fit: BoxFit.fill,
        ),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(20.0),
        ),
        elevation: 5,
        margin: EdgeInsets.all(10),
      ),
    );
  }
}

在这里检查结果是示例。

dressing = salad.find('Dressing')
if dressing:
    print(dressing.text)

这将返回from bs4 import BeautifulSoup data='''<Dressing>Italian</Dressing>''' salad = BeautifulSoup(data, 'xml') dressing = salad.find('Dressing') if dressing: print(dressing.text)

Italian

这将不返回任何内容。

答案 1 :(得分:0)

您可以在一行中使用if.. else

dressing = salad.find('Dressing').string if salad.find('Dressing') else None

语法是,
A if condition else B
如果条件通过,则执行A,否则执行B。